当前位置: 移动技术网 > IT编程>开发语言>PHP > ajax调用返回php接口返回json数据的方法(必看篇)

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

右溪记 阅读答案,是什么日子,于朦胧古装

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网