php程式碼如下:
<span><?php </span>header(<span>'Content-Type: application/json'</span>); header(<span>'Content-Type: text/html;charset=utf-8'</span>); <span>$email </span><span>= </span><span>$_GET[</span><span>'email'</span><span>]</span>; <span>$user </span><span>= </span><span>[]</span>; <span>$conn </span><span>= @</span>mysql_connect(<span>"localhost"</span>,<span>"Test"</span>,<span>"123456"</span>) <span>or die</span>(<span>"Failed in connecting database"</span>); mysql_select_db(<span>"Test"</span>,<span>$conn</span>); mysql_query(<span>"set names 'UTF-8'"</span>); <span>$query </span><span>= </span><span>"select </span><span><em>*</em></span><span> from UserInformation where email = '"</span><span>.</span><span>$email</span><span>.</span><span>"'"</span>; <span>$result </span><span>= </span>mysql_query(<span>$query</span>); <span>if </span>(<span>null </span><span>== </span>(<span>$row </span><span>= </span>mysql_fetch_array(<span>$result</span>))) <span>{ </span><span>echo </span><span>$_GET[</span><span>'callback'</span><span>]</span><span>.</span><span>"(no such user)"</span>; <span>} </span><span>else </span><span>{ </span><span>$user[</span><span>'email'</span><span>] </span><span>= </span><span>$email</span>; <span>$user[</span><span>'nickname'</span><span>] </span><span>= </span><span>$row[</span><span>'nickname'</span><span>]</span>; <span>$user[</span><span>'portrait'</span><span>] </span><span>= </span><span>$row[</span><span>'portrait'</span><span>]</span>; <span>echo </span><span>$_GET[</span><span>'callback'</span><span>]</span><span>.</span><span>"("</span><span>.</span>json_encode(<span>$user</span>)<span>.</span><span>")"</span>; <span>} </span><span>?></span>
<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
use JSONP (as I needed to go cross-domain), and returning the JSON code callback=?
and
getting the error.{"foo":"bar"}
jQuery17209314005577471107_1335958194322({"foo":"bar"})
2.第二個問題:
解析json資料。從上面的javascript可以看到,我沒有使用jquery.parseJSON()這些方法,開始使用這些方法,但是總是會報
VM219:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1的錯誤,後來不用jquery.parseJSON()這個方法,反而一切正常。不知為何。以上就介紹了ajax呼叫回傳php介面回傳json數據,包含了ajax,json方面的內容,希望對PHP教學有興趣的朋友有幫助。