codeigniter中的json解析问题

时间:2013-08-16 14:30:25

标签: jquery ajax codeigniter

我在codeigniter中遇到ajax / jquery问题。

在Html页面中,按下按钮时,我有一个按钮 调用以下处理程序。

按下按钮的处理程序:

function postMessage(e) {
    var postUrl = 'http://localhost/myProject/index.php/main/post_message';
    $.ajax({
        type: "POST",
        url: postUrl,
        success: successfulPost,
        dataType: "text"
    });      
}

ajax回调:

function successfulPost(data) {
    data = JSON.parse(data);
    document.write(data[0].hello);
}
控制器内的

服务功能:

function post_message() {   
    echo "[{\"hello\":\"world\"}]";
    return;  
}

问题是JSON.parse()似乎没有完成他的工作。

这些功能非常简单,所以我开始想也许codeigniter存在问题?

编辑:

奇怪的是,如果我将完全相同的json字符串放入JSON.parse()中 它被解析,问题是服务函数通过它。

编辑:

计算json字符串的字符数,它应该是13 但是我得到17 ......

编辑:

我现在认识到,尽管回声是正确完成的 有一些奇怪的字符引导HTTP响应的主体...... 诸如新行\ 0或制表符之类的东西 任何人都有任何线索的原因?

2 个答案:

答案 0 :(得分:0)

尝试在PHP中设置标题:

$data = array("hello" => "world");
header('Content-Type: application/json');
echo json_encode($data);

Returning JSON from a PHP Script

答案 1 :(得分:0)

在大多数情况下,在进行ajax调用时,您只需要坚持使用dataType: "JSON",就像这样:

$.ajax({
    type: "POST",
    url: postUrl,
    success: successfulPost,
    dataType: "JSON"
});

然后,在控制器中,您只需将普通的$_POST数组作为键值对,或者如果您使用的是codeigniter,则$this->input->post('whatever')无论如何在完成逻辑之后以及在回显之前都需要像这样使用json_encode($data_array)

function post_message()
{
    $data = array();
    $data['hello'] = "world";
    echo json_encode($data);
}

现在您可以执行以下操作:

function successfulPost(data) {
    // data = JSON.parse(data); not needed
    document.write(data.hello);
    // data.hello = world
}