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 相关文章推荐
生成缩略图
Oct 09 PHP
PHP VS ASP
Oct 09 PHP
功能齐全的PHP发送邮件类代码附详细说明
Jul 10 PHP
解决ajax+php中文乱码的方法详解
Jun 09 PHP
PHP CodeIgniter框架的工作原理研究
Mar 30 PHP
php动态添加url查询参数的方法
Apr 14 PHP
CodeIgniter实现从网站抓取图片并自动下载到文件夹里的方法
Jun 17 PHP
基于jQueryUI和Corethink实现百度的搜索提示功能
Nov 09 PHP
magento后台无法登录解决办法的两种方法
Dec 09 PHP
php装饰者模式简单应用案例分析
Oct 23 PHP
laravel框架实现敏感词汇过滤功能示例
Feb 15 PHP
php实现JWT验证的实例教程
Nov 26 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
phpBB BBcode处理的漏洞
2006/10/09 PHP
php出现Cannot modify header information问题的解决方法大全
2008/04/09 PHP
10 个经典PHP函数
2013/10/17 PHP
PHP实现的一致性Hash算法详解【分布式算法】
2018/03/31 PHP
10款非常有用的 Ajax 插件分享
2012/03/14 Javascript
JavaScript计时器示例分析
2015/02/05 Javascript
jquery插件validation实现验证身份证号等
2015/06/04 Javascript
AngularJS基础 ng-cloak 指令简单示例
2016/08/01 Javascript
使用伪命名空间封装保护独自创建的对象方法
2016/08/04 Javascript
Angularjs 制作购物车功能实例代码
2016/09/14 Javascript
jQuery中Find选择器用法示例
2016/09/21 Javascript
基于BootStrap与jQuery.validate实现表单提交校验功能
2016/12/22 Javascript
Bootstrap面板学习使用
2017/02/09 Javascript
Vue.js 插件开发详解
2017/03/29 Javascript
Angular2使用jQuery的方法教程
2017/05/28 jQuery
Redux实现组合计数器的示例代码
2018/07/04 Javascript
使用 Vue cli 3.0 构建自定义组件库的方法
2019/04/30 Javascript
javascript 高级语法之继承的基本使用方法示例
2019/11/11 Javascript
swiper4实现移动端导航栏tab滑动切换
2020/10/16 Javascript
Django框架中render_to_response()函数的使用方法
2015/07/16 Python
win系统下为Python3.5安装flask-mongoengine 库
2016/12/20 Python
Python读写docx文件的方法
2018/05/08 Python
对DJango视图(views)和模版(templates)的使用详解
2019/07/17 Python
Python-接口开发入门解析
2019/08/01 Python
Keras 快速解决OOM超内存的问题
2020/06/11 Python
如何在pycharm中安装第三方包
2020/10/27 Python
CSS3中border-radius属性设定圆角的使用技巧
2016/05/10 HTML / CSS
台湾流行服饰购物平台:OB严选
2018/01/21 全球购物
瑞士灯具购物网站:Lampenwelt.ch
2018/07/08 全球购物
介绍下java.util.Arrays类
2012/10/16 面试题
酒店开业庆典主持词
2014/03/21 职场文书
房屋出租协议书范本(标准版)
2014/09/24 职场文书
商务邀请函
2015/01/30 职场文书
2015年敬老月活动总结
2015/03/27 职场文书
CPU不支持Windows11系统怎么办
2021/11/21 数码科技
超越Nginx的Web服务器caddy优雅用法
2022/06/21 Servers