当前位置: 动力学知识库 > 问答 > 编程问答 >

php - $.getJSON fails on valid JSON?

问题描述:

I am pulling out my hair on JQuery/JSON issue where the response of $.getJSON function is not making sense.

So here is my Javascript code excerpt:

var jqxhr = $.getJSON("myPHPFunction.php", function() {

alert("success");

})

.success(function() { alert("second success"); })

.error(function() { alert("error"); })

.complete(function() { alert("complete"); });

The JSON returned by the PHP function is this:

{"sid":"12", "name":"somename", "email":"someemail"}

Full response:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head><title>Untitled Document</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body> {"sid":"12", "name":"somename", "email":"someemail"}

</body>

</html>

When I run the script, I get a dialog box saying error.

Several online validator have reported the JSON to be syntax-correct. Then why does JQuery fail? Note both the php and the script are in the same folder (on server) and same domain.

网友答案:

Your response must not contain any HTML!

Propberbly you also need to set the correct content type:

header("Content-Type: application/json");
echo('{"sid":"12", "name":"somename", "email":"someemail"}');
exit();

The code above should work.

Please note that you must not output any other code before the header line.

网友答案:

From the comments, you can't encapsulate the JSON in HTML markup. You'll need to ensure that the data returned ("View Source" is a good tool for verifying this) is pure JSON.

分享给朋友:
您可能感兴趣的文章:
随机阅读: