简体   繁体   中英

about json_encode and ajax dataType: “json”

In my ajax code:

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

Gives me an output [{"records":"1"}][{"records":"1"}] So I parsed it to json by adding dataType: "json" in my ajax code. But when I parsed it, it doesn't give me output but error on try-catch-block.

How do I get it to display as objects? In my PHP code, I'm doing it this way:

 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.

Add each entry to an array and then json encode that array, instead of json encoding each one separately. If you only have one call to json_encode, you will get valid 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);

That's not valid JSON. Make an array from your exist results and encode that .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM