欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-08 22:40:52
php代码如下:

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