更新:請參閱Anthony Grist對您的問題的評論,我錯過了您的JSON無效的事實。由於他沒有發佈答案,我會選擇它。
你JSON是無效的,因爲你返回兩個單獨的陣列,這一個:
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
這一個:
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
你不能這樣做,因爲頂層一個JSON文件必須是一個東西(一個對象或一個數組)。
您可以用屬性返回的對象爲每個陣列:
{
"vdata":
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
"datedata":
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
}
分析(見下文)後,就可以訪問這些數據是這樣的:
console.log(data.vdata[0].v); // "233"
console.log(data.datedata[0].date); // "2013-02-01"
或被兩個插槽的數組,每個插槽中都有一個陣列:
[
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
]
解析後(見下文),您可以訪問這些數據是這樣的:
console.log(data[0][0].v); // "233"
console.log(data[1][0].date); // "2013-02-01"
就個人而言,我更喜歡使用對象,因爲那顯然我訪問哪個陣列。
原來的答覆:
jQuery將解析JSON到你的一個對象,並傳遞到success
功能,然後你就可以訪問就像任何其他對象。在你的情況下,頂層是一個數組。所以:
$.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false,
success: function(data) {
// Use the line from above that suits the way
// you updated your JSON structure
}
});
旁註:async: false
已取消,將在某個時候被移除。做同步ajax請求通常不是一個好主意,它往往會在請求期間鎖定瀏覽器的用戶界面。相反,只需構造代碼以在觸發回調時繼續處理。
JSON表示單個對象或數組,所以不能返回兩個完全獨立的陣列。當你將它解析爲存儲在一個變量中的實際對象/數組時,它將如何工作?一個變量不能指向兩個單獨的東西。 – 2013-02-22 09:59:42
@AnthonyGrist是對的。你的json字符串無效。檢查http://jsonlint.com/ – Kris 2013-02-22 10:12:21
@Kris謝謝你的鏈接,我想我需要重建我的json字符串。 – Darth 2013-02-22 10:14:03