Im使用cakeHP 2.2.1
我有一个GoalsController,其中有一个add操作。此操作将发布的数据保存到目标表中。
在add.ctpim中使用jQueryajax方法将表单数据发布到上面所说的add操作。
我想要的是
- ajax方法将表单数据发布到目标/添加
- 目标/添加操作将数据保存到目标表
- 使用$this->Goal->id获取新插入行的id
- 将此id返回到ajax方法的onSuccess函数
步骤1、2、3运行良好。但是我不知道如何执行步骤4。
我知道php是服务器端,js是客户端。我有什么办法可以做到这一点吗?
一定要阅读Json视图上的书籍条目,并实现如下内容:
// 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发布到/goals/add.json
,Cake将识别.json
扩展与$this->set('_serialize')
的组合,并沿着{ id: 1 }
的行返回一个json字符串。
然后在您的$.ajax
函数中,进行这样的成功调用:
$.ajax({
url: '/goals/add.json',
dataType: 'json'
// other settings
success: function(response) {
alert(response.id); // response contains the returned data
}
});