ajax调用返回php接口返回json数据的方法(必看篇)


Posted in PHP onMay 05, 2017

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数据的方法(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
图片存储与浏览一例(Linux+Apache+PHP+MySQL)
Oct 09 PHP
谈谈新手如何学习PHP
Dec 14 PHP
PHP 巧用数组降低程序的时间复杂度
Jan 01 PHP
PHP中冒号、endif、endwhile、endfor使用介绍
Apr 28 PHP
php找出指定范围内回文数且平方根也是回文数的方法
Mar 23 PHP
php使用Image Magick将PDF文件转换为JPG文件的方法
Apr 01 PHP
PHP时间和日期函数详解
May 08 PHP
PHP实现对png图像进行缩放的方法(支持透明背景)
Jul 15 PHP
ThinkPHP中limit()使用方法详解
Apr 19 PHP
php常用数组函数实例小结
Dec 29 PHP
thinkPHP5框架实现基于ajax的分页功能示例
Jun 12 PHP
php7性能提升的原因详解
Oct 13 PHP
ThinkPHP 3.2.2实现事务操作的方法
May 05 #PHP
PHP实现Session入库/存入redis的方法
May 04 #PHP
ThinkPHP中Widget扩展的两种写法及调用方法详解
May 04 #PHP
PHP+jQuery实现滚屏无刷新动态加载数据功能详解
May 04 #PHP
PHP调用Mailgun发送邮件的方法
May 04 #PHP
PHP实现图片的等比缩放和Logo水印功能示例
May 04 #PHP
Yii2数据库操作常用方法小结
May 04 #PHP
You might like
PHP 字符串操作入门教程
2006/12/06 PHP
通过修改Laravel Auth使用salt和password进行认证用户详解
2017/08/17 PHP
PHP 中魔术常量的实例详解
2017/10/26 PHP
Laravel5.4框架中视图共享数据的方法详解
2019/09/05 PHP
js每次Title显示不同的名言
2008/09/25 Javascript
javascript实现上传图片并预览的效果实现代码
2011/04/11 Javascript
js中方法重载如何实现?以及函数的参数问题
2013/08/01 Javascript
Java/JS获取flash高宽的具体方法
2013/12/27 Javascript
jquery选择器之基本过滤选择器详解
2014/01/27 Javascript
Extjs Label的 fieldLabel和html属性值对齐的方法
2014/06/15 Javascript
原生javascript实现拖动元素示例代码
2014/09/01 Javascript
2014 年最热门的21款JavaScript框架推荐
2014/12/25 Javascript
JCrop+ajaxUpload 图像切割上传的实例代码
2016/07/20 Javascript
nodeJS删除文件方法示例
2016/12/25 NodeJs
基于Vue实现timepicker
2017/04/25 Javascript
JS实现仿UC浏览器前进后退效果的实例代码
2017/07/17 Javascript
nodejs项目windows下开机自启动的方法
2017/11/22 NodeJs
JQuery Ajax动态加载Table数据的实例讲解
2018/08/09 jQuery
解决vue scoped html样式无效的问题
2020/10/24 Javascript
Python的一些用法分享
2012/10/07 Python
详解python的数字类型变量与其方法
2016/11/20 Python
详解python调度框架APScheduler使用
2017/03/28 Python
Sublime开发python程序的示例代码
2018/01/24 Python
使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法
2018/06/22 Python
详解有关PyCharm安装库失败的问题的解决方法
2020/02/02 Python
python模式 工厂模式原理及实例详解
2020/02/11 Python
编译 pycaffe时报错:fatal error: numpy/arrayobject.h没有那个文件或目录
2020/11/29 Python
flask框架中的cookie和session使用
2021/01/31 Python
美国当红的名品折扣网:Gilt Groupe
2016/08/15 全球购物
Notino法国:购买香水和化妆品
2019/04/15 全球购物
法国低价在线宠物商店:bitiba.fr
2020/07/03 全球购物
营销部内勤岗位职责
2014/04/30 职场文书
购房协议书范本
2014/10/02 职场文书
长江七号观后感
2015/06/11 职场文书
单位车辆管理制度
2015/08/05 职场文书
Mybatis-Plus进阶分页与乐观锁插件及通用枚举和多数据源详解
2022/03/21 Java/Android