处理json数组CAKEPHP

时间:2014-11-04 09:27:39

标签: json cakephp

这是我的javascript snipet

<script type="text/javascript">
$(document).ready(function() {
        $('form#FormId button.btn').click(function(event){
            $.ajax({
                type: "POST",
                url: "/controller/edit",
                data: $("#FormId").serialize(), 
                success: function(response) {
                    alert(response.message);
                    alert(response['message']);
                }
            }); 
        });
    });

这是我的控制器动作

public function edit() {
    $this->autoRender = false; // We don't render a view in this example
    $this->request->onlyAllow('ajax'); // No direct access via browser URL

    echo json_encode(array('message'=>'Welcome','type'=>'success'));

    exit;
}

javascript上的两个警报都返回&#34; undefined&#34;怎么处理?

4 个答案:

答案 0 :(得分:1)

所以没人知道这是正确的。

您需要使用JSON view

了解如何使用this section

启用
class PostsController extends AppController {
    public $components = array('RequestHandler');

    public function index() {
        $this->request->onlyAllow('ajax');
        $this->set(array(
            'data' => array('message'=>'Welcome','type'=>'success'),
            '_serialize' => 'data',
        ));
    }
}

Cake现在将自动设置正确的标题,序列化为JSON并且不呈现布局。

作为旁注,您的代码alert(response.message);不起作用,因为response是一个字符串。您的标题为text/html而不是application/json。试试console.log(response),您会看到它只是一个字符串。

答案 1 :(得分:0)

我使用控制器中的以下代码

来实现此功能
public function edit()
{
    $this->RequestHandler->respondAs('json'); // Very important without this it will not work
    $this->autoRender = false;
    $data = array('message'=>'Welcome','type'=>'success');
    return json_encode($data);
}

答案 2 :(得分:0)

尝试添加

 dataType: 'json',

到你的ajax方法。

如果不起作用,试试这个: 添加

$this->response->type('text/plain');

到您的索引方法。

即布劳尔不知道json格式文本。 你用这个测试的broswer是什么?使用F12打开开发人员工具包来检查服务器响应是什么,是一个对象

答案 3 :(得分:-1)

根据我的经验,回应内容不起作用。您应该返回json_encoded数据。

这会使您的edit()函数看起来像这样:

public function edit()
{
    $this->autoRender = false;
    $this->request->onlyAllow('ajax');

    return json_encode(array('message' => 'Welcome', 'type' => 'success'));
}

确保它有效;只需提醒整个响应对象,看看返回的内容。