XML爲大多數ajax請求添加了很多額外的標記。如果您期待某種帶有數據實體的列表,那麼以JSON格式發送它們是一種方法。
我用JSON來獲取數據相當龐大的數組。
首先,JSON只是Javascript對象表示法,意思是Ajax請求會請求一個實際上將被評估爲Javascript對象的String。
某些瀏覽器支持JSON解析功能。其他需要一點幫助。我用this little library解析了我開發的所有webapps中的responseText,並且沒有任何問題。
現在您已經知道JSON是什麼以及如何使用它了,下面介紹PHP代碼的外觀。
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response);
嘗試一下,看看它有什麼回聲。我使用php 5.4數組聲明語法,因爲它很酷! :)
當請求通過Ajax的數據,你會怎麼做:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
回顧:
- JSON解析需要通過JSON2庫一點點幫助
- PHP可以把地圖作爲JSON
- 成功布爾值被廣泛用作「成功/不成功」標誌
此外,如果您使用jQuery,則可以在$ .ajax調用中設置dataType:「json」屬性以在成功回調中接收JSON響應。
爲什麼不把它作爲JSON(如果可用)?而不是XML – 2012-03-07 02:02:25
@Mahan我不太熟悉JSON ..是否允許更大的數據傳輸?我看起來它.. – tinks 2012-03-07 02:03:19
是的...我一直使用JSON 2年,它比XML快得多,試着在這裏研究它http://www.w3schools.com/json/default.asp – 2012-03-07 02:15:42