使用cakeHP中的jQuery ajax方法,将新保存的数据的id返回给ajax onSuccess



Im使用cakeHP 2.2.1

我有一个GoalsController,其中有一个add操作。此操作将发布的数据保存到目标表中。

add.ctpim中使用jQueryajax方法将表单数据发布到上面所说的add操作。

我想要的是

  1. ajax方法将表单数据发布到目标/添加
  2. 目标/添加操作将数据保存到目标表
  3. 使用$this->Goal->id获取新插入行的id
  4. 将此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
    }
});

最新更新