在我的ajax代码中:
$.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.
将每个条目添加到数组中,然后对该数组进行 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);
这不是有效的 JSON。从现有结果中创建一个数组并对其进行编码。