您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

ajax实现调用返回php接口返回json数据的方法

2025/6/26 4:12:43发布10次查看
本篇文章主要介绍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()这个方法,反而一切正常。不知为何。
相关推荐:
php中的ini配置原理详解_php基础
php格式化json函数示例代码_php技巧
php中{}大括号是什么意思_php基础
以上就是ajax实现调用返回php接口返回json数据的方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product