寫 Ajax 時最惱人的莫過於後台回傳的東西看不見。 alert 一個對象只會得到 [object Object],這時候 JSON.stringify() 就派上用場——它把 JSON 對象序列化成字串,內容一目了然。
複製代碼 代碼如下:
$(document).ready(function() {
$.ajax({
type: "post",
dataType: "json",
url: '/centermanage/modules/admin/index.php?task=getequipmentinfo',
data: "&id=" + id,
error: function(msg){
alert(JSON.stringify(msg));
},
success: function(msg) {
alert(JSON.stringify(msg));
})
})
值得多說兩句的是:error 與 success 兩個回調裡都加上 JSON.stringify,是因為出問題時我們更需要看到伺服器到底回了什麼——很多時候所謂的「解析失敗」,真相是後端吐了一段 PHP 錯誤訊息或 HTML。
實際除錯時,比 alert 更好用的做法有幾個:
console.log(JSON.stringify(msg)),告別一路按確定。JSON.stringify(msg, null, 2),巢狀結構也能讀。dataType: "text" 先拿原始響應,確認不是格式問題再談解析。注意 stringify 是單向的:函數與 undefined 屬性會被丟棄,循環引用的對象則會直接拋錯。它適合拿來看,不適合拿來做完整備份。