gpt4 book ai didi

javascript - 无法从 Cakephp 3 Controller 获得 json 响应

转载 作者:行者123 更新时间:2023-11-30 15:58:15 25 4
gpt4 key购买 nike

我正在尝试向 Cakephp 3 Controller 发送 ajax 请求。

controller会从model中找到数据返回给同一个view显示,

View 和js函数如下

<script type = "text/javascript" language = "javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type : "POST",
url : "<?php echo $this->Url->build(['controller' => 'users', 'action' => 'getByCategories', '_ext' => 'json']); ?>",
success: function (data){
console.log(JSON.stringify(data));
}
});
});
});</script>

以上函数在 Controller 的索引 View 中。

单击按钮后,将向同一 Controller 中的 getByCategories 函数发送一个请求。

getByCategories函数如下

public function getByCategories()
{
$id = 33;
$this->request->allowMethod(['ajax']);
$this->autoRender = false;
$cat = $this->Users->Categories->get($id);
if ($this->Users->Categories->childCount($cat) > 0)
{
$result = $this->Users->Categories->find('all', ['conditions' => ['parent_id' => $id]]);
$this->set(compact($result));
$this->set('_serialize', $result);
}
else
{
$result['Machines'] = $this->Users->Machines->find('all', ['conditions' => ['category_id' => $id]]);
$result['Medias'] = $this->Users->Medias->find('all', ['conditions' => ['category_id' => $id]]);
$this->set(compact($result));
$this->set('_serialize', $result);
}
}

此函数的 ajax 响应始终为空,但 debugkit 正确显示 _serialize 变量。

我在 routes.php 文件中启用了 json 扩展。 debugkit中this调用的变量如下

debugkit varables

如果有人可以指导从 ajax 响应中的 debugkit 获取变量,我将不胜感激

提前致谢

最佳答案

看起来你很接近,只是误解了 _serialize(可能是 setcompact)是如何工作的。检查the manual对于所有细节,但是您应该在 _serialize 中设置的是 names of 变量的列表,或者 true 以序列化所有内容。

此外,如果您将 compactset 一起使用,您可以为其指定 变量的名称,而不是变量本身。

所以,你应该在那里使用的可能是:

$this->set(compact('result'));
$this->set('_serialize', ['result']);

关于javascript - 无法从 Cakephp 3 Controller 获得 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38169410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com