我正在尝试使用 JQuery 从网页发送 JSON 数据,如下所示:
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
在 cake2.2 中,我有一个名为 Ajax 的 Controller ,它有一个名为“login”的方法,如下所示:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input(); // MY QUESTION IS WITH THIS LINE
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
我只是想看看我是否将正确的数据传递给了 Controller 。如果我使用这一行:
$data = $this->request->input();
我可以看到调试打印输出:
{username: "wiiNinja", password: "isCool"}
我在 CakePHP 手册 2.x 中读到,在“访问 XML 或 JSON 数据”下,它建议这个调用来解码数据:
$data = $this->request->input('json_decode');
当我调试 print $data 时,我得到“null”。我究竟做错了什么?我从 Javascript 传入的数据不正确吗?还是我没有正确调用解码?
感谢任何建议。
=============我自己的编辑========
通过实验发现自己的错误:
当通过 Javascript 发布时,而不是这一行:
data: '{username: "wiiNinja", password: "isAnub"}',
将其更改为:
data: '{"username": "wiiNinja", "password": "isAnub"}',
和
在 Controller 代码中,更改这一行:
$data = $this->request->input('json_decode');
收件人:
$data = $this->request->input('json_decode', 'true');
有效。
邓纳姆兹,
当我按照您的建议检查我的 Controller 代码中的“$this->request->params”数组时,它包含以下内容:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
如您所见,我要查找的数据不存在。我已经有了正确的路线代码。这与 2.x 的文档在这里所说的一致:
http://book.cakephp.org/2.0/en/controllers/request-response.html
到目前为止,我发现使它起作用的唯一方法是上面“我自己的编辑”中所述的方法。但是,如果向服务器发送 JSon 字符串不是正确的做法,我想解决这个问题,因为最终,我将不得不处理将发送 JSon 对象的第三方代码。
最佳答案
您在处理数据时苦苦挣扎的原因是您发送的是 jQuery 字符串,而不是正确的 javascript 对象 (JSON)。
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
现在,数据将以 $this->request->params
中的 PHP 数组形式提供。
也用于发送 JSON 响应,please see this manual page .您的大部分代码都可以减少到只有 2 行...
//routes.php
Router::parseExtensions('json');
//Controller that sends JSON
$this->set('_serialize', array('data'));
关于javascript - cakephp 2.2 在 Controller 中检索 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11443875/