我试图将一些 json 传递给 cakePHP 2.5 中的 Controller 并再次返回它以确保一切顺利。
但是我没有收到回复内容。刚刚200成功。通过阅读文档,我的印象是,如果我传递一些 json,则 responseHandler 将返回 json 作为响应。
不确定我错过了什么。
正在传递的数据
var neworderSer = $(this).sortable("serialize");
给出
item[]=4&item[]=3&item[]=6&item[]=5&item[]=7
appController.php
public $components = array(
'DebugKit.Toolbar',
'Search.Prg',
'Session',
'Auth',
'Session',
'RequestHandler'
);
索引.ctp
$.ajax({
url: "/btstadmin/pages/reorder",
type: "post",
dataType:"json",
data: neworderSer,
success: function(feedback) {
notify('Reordered pages');
},
error: function(e) {
notify('Reordered pages failed', {
status: 'error'
});
}
});
PagesController.php
public function reorder() {
$this->request->onlyAllow('ajax');
$data = $this->request->data;
$this->autoRender = false;
$this->set('_serialize', 'data');
}
更新: 我现在已将以下内容添加到 routes.php
Router::parseExtensions('json', 'xml');
并且我已经将我的 Controller 更新为
$data = $this->request->data;
$this->set("status", "OK");
$this->set("message", "You are good");
$this->set("content", $data);
$this->set("_serialize", array("status", "message", "content"));
现在一切正常。
最佳答案
应提供适当的Accept
header 或扩展
为了让请求处理程序能够选择正确的 View ,您需要发送适当的 Accept
header (application/json
),或者提供一个扩展名,在您的情况下为 .json
。为了完全识别扩展,需要启用扩展解析。
参见 http://book.cakephp.org/...views.html#enabling-data-views-in-your-application
View 只序列化 View 变量
JSON View 仅自动序列化 View 变量,从您显示的代码来看,您似乎从未设置过名为 data
的 View 变量。
参见 http://book.cakephp.org/...views.html#using-data-views-with-the-serialize-key
需要渲染的 View
你不应该禁用 auto rendering除非你有充分的理由,并且在你的情况下最终也手动调用 Controller:render()
。目前,您的操作甚至不会尝试渲染任何内容。
CakeRequest::onlyAllow() 用于 HTTP 方法
CakeRequest::onlyAllow()
(顺便说一句是 deprecated as of CakePHP 2.5 )用于指定允许的 HTTP
方法,即 GET
,POST
、PUT
等。虽然使用任何可用的检测器(例如 ajax
)都可以工作,但您可能不应该依赖它。
长话短说
您的 reorder()
方法应该更像这样:
public function reorder() {
if(!$this->request->is('ajax')) {
throw new BadRequestException();
}
$this->set('data', $this->request->data);
$this->set('_serialize', 'data');
}
最后,如果您不想/不能使用 Accept
header ,您需要将 .json
扩展名附加到 AJAX 的 URL要求:
url: "/btstadmin/pages/reorder.json"
然后在您的 routes.php
中启用扩展解析,例如:
Router::parseExtensions('json');
ps
参见 Cakephp REST API remove the necessity of .format 了解在不使用扩展的情况下使用 JSON View 的方法。
关于ajax - 使用 cakephp 的简单 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096102/