2012-05-30 67 views
0

在我的Ajax代码:约json_encode和Ajax数据类型: “JSON”

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

给了我一个输出[{ “记录”: “1”}] [{ “记录”: “1”} ]因此,我通过在我的ajax代码中添加dataType:“json”来将它解析为json。但是当我解析它时,它不会给我输出,但在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. 

回答

2

这不是有效的JSON。根据你现有的结果做一个数组并编码

5

将每个条目添加到一个数组,然后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);