cakephp 2.2检索控制器中的json数据

时间:2012-07-12 01:26:11

标签: javascript json cakephp

我正在尝试使用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的控制器,它有一个名为“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;
}

我只想知道我是否将正确的数据传递给控制器​​。如果我使用这一行:

$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"}',

在控制器代码中,更改此行:

$data = $this->request->input('json_decode');

要:

$data = $this->request->input('json_decode', 'true');

有效。


Dunhamzzz,

当我按照您的建议,并检查我的控制器代码中的“$ 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对象的第三方代码。

1 个答案:

答案 0 :(得分:1)

您正在努力解决数据的原因是因为您使用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'));