【问题标题】:about json_encode and ajax dataType: "json"关于 json_encode 和 ajax 数据类型:“json”
【发布时间】:2012-05-30 03:48:55
【问题描述】:

在我的 ajax 代码中:

$.ajax({
        url: CI_ROOT + "isUserExist",
        type: "GET",
        data: {recepient: recepient},
        success: function(r) {
            console.log(r)
        }
})

给我一​​个输出 [{"records":"1"}][{"records":"1"}] 所以我通过添加 dataType:" 将其解析为 json json" 在我的 ajax 代码中。但是当我解析它时,它没有给我输出,而是在 try-catch-block 上出错。

如何让它显示为对象? 在我的 PHP 代码中,我是这样做的:

 for ($i = 0; $i < count($matches[0]); $i++) {
     echo json_encode($this->searchmodel->doesUsersExists($matches[0][$i]));
 } //gets the user id of the user from a given string.

【问题讨论】:

    标签: php javascript json


    【解决方案1】:

    将每个条目添加到一个数组中,然后对该数组进行 json 编码,而不是分别对每个条目进行 json 编码。如果您只调用一次 json_encode,您将获得有效的 JSON:

    $result = array();
    for ($i = 0; $i < count($matches[0]); $i++) {
         $result[] = $this->searchmodel->doesUsersExists($matches[0][$i]);
    } //gets the user id of the user from a given string.
    
    echo json_encode($result);
    

    【讨论】:

      【解决方案2】:

      这不是有效的 JSON。从现有结果中创建一个数组并编码 that

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-17
        • 2014-07-11
        • 2019-06-19
        • 2011-07-17
        • 1970-01-01
        • 1970-01-01
        • 2013-11-17
        • 1970-01-01
        相关资源
        最近更新 更多