jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR) ] )
url:提供 JSON 資料的端點data:查詢字串參數物件 (選填)success:請求成功回調,data 為解析後的 JS 物件/陣列{ "Unid":1, "CustomerName":"宋江", "Memo":"天魁星", "Other":"黑三郎" }
$.getJSON('webdata/Json_1.ashx', function(data) {
// data 直接是物件
$('#divMsg').text(data.CustomerName); // "宋江"
// 遍歷所有屬性
var html = '';
$.each(data, function(k, v) {
html += k + ':' + v + '<br/>';
});
$('#divMsg').html(html);
});
[
{ "Unid":1, "CustomerName":"宋江", "Memo":"天魁星", "Other":"黑三郎" },
{ "Unid":2, "CustomerName":"吳用", "Memo":"天機星", "Other":"智多星" }
]
$.getJSON('webdata/Json_1.ashx', function(data) {
// data 是陣列 [{...}, {...}]
var html = '';
$.each(data, function(index, item) { // index: 0, 1
$.each(item, function(prop, value) { // 遍歷單筆物件屬性
html += prop + ':' + value + '<br/>';
});
html += '<hr/>';
});
$('#divMsg').html(html);
});
| 回傳結構 | data 型別 | 遍歷方式 |
|---|---|---|
單一物件 {...} | Object | $.each(data, fn(k,v)) |
物件陣列 [{...}, {...}] | Array | $.each(data, fn(i, item)) → $.each(item, fn(k,v)) |
Content-Type: application/json。dataType:'jsonp') 或 CORS。cache:false 或 URL 加時間戳。$.ajax({
url: 'api/data',
dataType: 'json',
cache: false,
success: function(data) { /* ... */ },
error: function(jqXHR, textStatus, errorThrown) {
console.error('JSON 請求失敗:', textStatus, errorThrown);
}
});
理解 JSON 結構與 $.each 遍歷模式,是前後端分離開發的基礎技能。