1. 程式人生 > >jQuery AJAX獲取JSON資料解析多種方式示例

jQuery AJAX獲取JSON資料解析多種方式示例

$(function () { //方式一 Ajax方式獲取Json資料 $.ajax({ url: 'jsondata.ashx?type=1', type: 'GET', dataType: 'json', timeout: 1000, cache: false, beforeSend: LoadFunction, //載入執行方法
error: erryFunction, //錯誤執行方法 success: succFunction //成功執行方法 }) function LoadFunction() { $("#list").html('載入中...'); } function erryFunction() { alert("error"); } function
succFunction(tt) {
var json = eval(tt); //陣列 var tt = ""; $.each(json, function (index) { //迴圈獲取資料 var Id = json[index].id; var Name = json[index].name; var
Age = json[index].age; var Score = json[index].score; tt += Id + "___" + Name + "___" + Age + "___" + Score + "<br>"; }); $("#list").html(''); $("#list").html(tt); } //方式二 Json方式獲取資料 $.getJSON( "jsondata.ashx?type=1", function (data) { //迴圈獲取資料 var tt = ""; $.each(data, function (k, v) { $.each(v, function (kk, vv) { tt += kk + ":" + vv + "___"; }); tt += "<br/>"; }); $("#list2").html(tt); } ); //方式三 Ajax方式獲取Json層級資料 $.ajax({ url: 'jsondata.ashx?type=3', type: 'GET', dataType: 'json', timeout: 1000, cache: false, beforeSend: LoadFunction1, //載入執行方法 error: erryFunction1, //錯誤執行方法 success: succFunction1 //成功執行方法 }) function LoadFunction1() { $("#list3").html('載入中...'); } function erryFunction1() { alert("error"); } function succFunction1(tt) { var json = eval(tt); //陣列 var tt = ""; $.each(json, function (index) { //迴圈獲取資料 var Id = json[index].id; var Name = json[index].name; var Age = json[index].age; var Score = json[index].score; tt += Id + "___" + Name + "___" + Age + "___"; $.each(Score, function (k, v) { tt += k + ":" + v + "___"; }) tt += "<br/>"; }); $("#list3").html(''); $("#list3").html(tt); } //方式四 Json方式獲取層級資料 $.getJSON( "jsondata.ashx?type=3", function (json) { //迴圈獲取資料 var tt = ""; $.each(json, function (index) { //迴圈獲取資料 var Id = json[index].id; var Name = json[index].name; var Age = json[index].age; var Score = json[index].score; tt += Id + "___" + Name + "___" + Age + "___"; $.each(Score, function (k, v) { tt += k + ":" + v + "___"; }) tt += "<br/>"; }); $("#list4").html(''); $("#list4").html(tt); } ); });