[英]PHP json_encode then getJSON issue in javascript
抱歉,如果這仍然是該主題的另一個話題,但是自數小時以來我一直在努力,但找不到解決方案。 我正在嘗試從Mysql數據庫獲取數據,使用php創建JSON,然后在javascript中解析此JSON。
這是我的json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
然后我嘗試將其解析為Java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
當我用數據文件data.json中的結果替換localhost / json.php時,它可以工作,當我用firefox打開localhost / json.php時,我可以看到JSON表...所以我不知道為什么它沒有使用localhost / json.php。 我的php代碼或javascript代碼錯誤嗎?
在此先感謝您的幫助 !
試試這個在PHP
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
試試這個方法
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
我認為您的Web應用程序服務器(例如Apache或nginx)默認發送Content-Type: text/html
或類似的內容作為json.php
文件。 另一方面,看起來$.getJSON
方法需要一個application/json
內容類型字段。
嘗試添加:
header("Content-Type: application/json");
到json.php
文件的頂部。
編輯-其他信息:
我在$.getJSON
方法的原始文檔中$.getJSON
它是否實際上需要特定的Content-Type,因此我查看了源代碼:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
這是getJSON
jQuery 1.7.1(我希望您使用的版本)的源代碼行,如您所見,它調用jQuery.get
,最后一個參數設置為"json"
。
反過來, jQuery.get
文檔揭示了此參數的意思是:
服務器期望的數據類型。 默認值:Intelligent Guess(xml,json,腳本或html)。
因此,當您調用$.getJSON("/url/to/file", ...)
,第一個參數應該是JSON。 如果從答案的頂部添加PHP代碼,則您的Web應用程序服務器會將php文件的輸出屏蔽為JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.