简体   繁体   中英

I can't parse JSON by JQuery

I need to send some data to JQuery by JSON. There is my code below:

$name = "test";
$answer = array("code" => 1, "name" => $name);
echo json_encode($answer);
console.log(data); 
var response = JSON.parse(data);

Console says:

{"code":1,"name":"test"}

VM635:2 Uncaught SyntaxError: Unexpected token in JSON at position 2

at JSON.parse ()

at Object.onAjaxSuccess [as success] (auth.js:32)

at u (jquery.js:2)

at Object.fireWith [as resolveWith] (jquery.js:2)

at k (jquery.js:2)

at XMLHttpRequest. (jquery.js:2)

Help me :O

我认为你必须删除 JSON.parse.... 因为你已经用 json_encode 解析了 json

Let jQuery do the work:

$.getJSON( "ajax/test.php", function( data ) {
     console.log(data);
}

That's just a wrapper to $.ajax. When you send the data from the PHP, you should send Content-Type too, not absolutely necessary but definitely best practice.

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