在cakePHP中使用jQueryAjax方法,将新保存的数据的id返回到ajax onSuccess
Im使用CakePHP2.2.1 我有一个GoalsController,其中有一个add动作。此操作将发布的数据保存到目标表 在add.ctpim中,使用jqueryajax方法将表单数据发布到上述add操作 我想要的是在cakePHP中使用jQueryAjax方法,将新保存的数据的id返回到ajax onSuccess,jquery,ajax,cakephp,Jquery,Ajax,Cakephp,Im使用CakePHP2.2.1 我有一个GoalsController,其中有一个add动作。此操作将发布的数据保存到目标表 在add.ctpim中,使用jqueryajax方法将表单数据发布到上述add操作 我想要的是 ajax方法将表单数据发布到目标/添加 目标/添加操作将数据保存到目标表 使用$this->Goal->id获取新插入行的id 将此id返回到ajax方法的onSuccess函数 步骤1、2、3工作正常。但我不知道如何实施步骤4 我知道php是服务器端,js是客户端等等。有什
我知道php是服务器端,js是客户端等等。有什么方法可以做到这一点吗?请务必阅读上的书籍条目,并执行以下操作:
// Routes.php
Router::parseExtensions('json');
// Controller
$this->set('id', $this->Goal->id);
$this->set('_serialize', array('id'));
// AppController.php
public $components = array('RequestHandler'); // Or add 'RequestHandler' to the existing list.
$.ajax({
url: '/goals/add.json',
dataType: 'json'
// other settings
success: function(response) {
alert(response.id); // response contains the returned data
}
});
然后,您需要将您的ajax帖子发送到/goals/add.json
,然后Cake将识别.json
扩展以及$this->set(“\u serialize”)
,并沿{id:1}
行返回一个json字符串
然后在$.ajax
函数中,进行如下成功调用:
// Routes.php
Router::parseExtensions('json');
// Controller
$this->set('id', $this->Goal->id);
$this->set('_serialize', array('id'));
// AppController.php
public $components = array('RequestHandler'); // Or add 'RequestHandler' to the existing list.
$.ajax({
url: '/goals/add.json',
dataType: 'json'
// other settings
success: function(response) {
alert(response.id); // response contains the returned data
}
});
答案很好,但不要忘记需要将RequestHandler添加到组件中list@Dunhamzzz谢谢你的回复。我试了你的建议。但我在Firebug控制台中收到500个内部错误。这就是原因:啊,您需要为您的操作创建一个视图文件,只需在正常位置创建一个
add.ctp
。不理想,因为您永远不会使用它(可以将其用作非javascript后备)@JoséLorenzo我是否需要创建一个名为add.json的额外文件才能使用此方法?我现在已经把表单元素和ajax代码放在add.ctp文件中了。很抱歉,你说得对,奇怪的是它正在寻找一个json视图文件,我认为它会跳过这个文件,因为你正在使用$this->set(''u serialize',array('id'))代码>。尝试创建一个View/Goals/json/add.ctp
和echo-json_-encode(compact('id'))代码>在它里面