ajax调用返回php接口返回json数据

时间:2021-05-07 17:52:42

php代码如下:

<?php

header('Content-Type: application/json');
header('Content-Type: text/html;charset=utf-8');

$email = $_GET['email'];

$user = [];

$conn = @mysql_connect("localhost","Test","123456") or die("Failed in connecting database");
mysql_select_db("Test",$conn);
mysql_query("set names 'UTF-8'");
$query = "select * from UserInformation where email = '".$email."'";
$result = mysql_query($query);
if (null == ($row = mysql_fetch_array($result))) {
echo $_GET['callback']."(no such user)";
} else {
$user['email'] = $email;
$user['nickname'] = $row['nickname'];
$user['portrait'] = $row['portrait'];
echo $_GET['callback']."(".json_encode($user).")";
}

?>
js代码如下:

<script>
$.ajax({
url: "http://test.localhost/UserInterfaceForChatroom/UserInformation.php?email=pshuyue@gmail.com",
type: "GET",
dataType: 'jsonp',
// crossDomain: true,
success: function (result) {
// data = $.parseJSON(result);
// alert(data.nickname);
alert(result.nickname);
}
});
</script>

其中遇到了两个问题:

1.第一个问题:

Uncaught SyntaxError: Unexpected token :

解决方案如下:

This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.

This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})

Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:

$ret['foo'] = "bar";
finish
();

function finish() {
header
("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}

Hopefully that will help someone in the future.

2.第二个问题:
解析json数据。从上面的javascript中可以看到,我没有使用jquery.parseJSON()这些方法,开始使用这些方法,但是总是会报 VM219:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 的错误,后来不用jquery.parseJSON()这个方法,反而一切正常。不知为何。