在我的ajax代码中:
$.ajax({
url: CI_ROOT + "isUserExist",
type: "GET",
data: {recepient: recepient},
success: function(r) {
console.log(r)
}
})
给我一个输出[{"records":"1"}][{"records":"1"}]所以我通过添加dataType: "将其解析为json我的 ajax 代码中的“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);
关于php - 关于 json_encode 和 ajax dataType : "json",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809761/