您好,登錄后才能下訂單哦!
如何調(diào)用ajax返回php接口?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
php是一個嵌套的縮寫名稱,是英文超級文本預(yù)處理語言,它的語法混合了C、Java、Perl以及php自創(chuàng)新的語法,主要用來做網(wǎng)站開發(fā),許多小型網(wǎng)站都用php開發(fā),因?yàn)閜hp是開源的,從而使得php經(jīng)久不衰。
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; }
關(guān)于如何調(diào)用ajax返回php接口問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。