久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

ajax調用返回php接口返回json數據的方法(必看篇)

下面小編就為大家帶來一篇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()這個方法,反而一切正常。不知為何。

以上這篇ajax調用返回php接口返回json數據的方法(必看篇)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。

【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。

相關文檔推薦

主站蜘蛛池模板: 中文字幕日韩欧美 | 国产精品永久久久久 | 天天操夜夜看 | 亚洲欧美在线观看 | 欧美精品99 | 亚洲精品一区二区三区在线 | 青青久久 | 午夜婷婷激情 | 欧美成人hd| 精品一区国产 | 欧美黄色免费网站 | 国产精品1区 | 久草欧美视频 | 欧美一区二区久久 | 国产成人久久久 | 免费激情av| 中文字幕在线观看一区 | 91伦理片 | 亚洲精品国产电影 | 久久久九九九九 | 国产高清精品在线 | 久久国产精品99久久久久久丝袜 | 久久成人精品视频 | 成人亚洲视频 | 久久视频精品在线 | 男女羞羞视频在线免费观看 | 亚洲天堂色 | 欧美一区二区在线观看 | 免费看国产a| 成人无遮挡毛片免费看 | 在线免费观看欧美 | 欧美一级二级三级视频 | 欧美一区二区三区四区视频 | 在线观看av不卡 | 精品久久一区 | 国产aaaaav久久久一区二区 | 亚洲一区在线日韩在线深爱 | 国产视频亚洲视频 | 亚洲国产精品99久久久久久久久 | 久久精品伊人 | 欧美日韩成人影院 |