ajax调用返回php接口返回json数据的方法(必看篇)
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()这个方法,反而一切正常。不知为何。
以上这篇ajax调用返回php接口返回json数据的方法(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: 一段很有意思的代码
推荐阅读
-
ajax调用返回php接口返回json数据的方法(必看篇)
-
php写app接口并返回json数据的实例(分享)
-
ajax调用返回php接口返回json数据的方法(必看篇)
-
PHP封装返回Ajax字符串和JSON数组的方法
-
php实例-php写app接口并返回json数据的实例(分享)
-
Ajax调用restful接口传送Json格式数据的方法
-
将PHP程序中返回的JSON格式数据用gzip压缩输出的方法,jsongzip_PHP教程
-
jQuery中ajax请求后台返回json数据并渲染HTML的方法
-
API接口调用并处理返回的json数据
-
ThinkPHP通过AJAX返回JSON的两种实现方法,thinkphpjson_PHP教程