2012-09-15 59 views
0

我有這樣的JSON:如何使用JQuery來解析這個json?

{ 
    "jsonDept": [ 
    { 
     "Id": "1", 
     "DeptName": "aaaa " 
    }, { 
     "Id": "2", 
     "DeptName": "bbb " 
    }, { 
     "Id": "6", 
     "DeptName": "ccc " 
    }, { 
     "Id": "7", 
     "DeptName": "ddd " 
    }, { 
     "Id": "8", 
     "DeptName": "eee " 
    }, { 
     "Id": "9", 
     "DeptName": "fff " 
    }, { 
     "Id": "12", 
     "DeptName": "haha " 
    }, { 
     "Id": "13", 
     "DeptName": "test1 " 
    }, { 
     "Id": "14", 
     "DeptName": "test2 " 
    }, { 
     "Id": "10", 
     "DeptName": "tmd " 
    }, { 
     "Id": "11", 
     "DeptName": "tnnd " 
    } 
    ] 
} 

而且我的JQuery:

function loadDepartmentList() { 
    $.ajax({ 
     url: "QueryDepartment.ashx", 
     //data: "", 
     type: "GET", 
     dataType: 'json', 
     success: function (data) { 
      // how to read json here? this is not working 
      $.each(data, function() { 
       alert("Name: " + this.DeptName); 
      }); 
     } 
    }) 
} 

但警報顯示爲 「不確定」,只有彈出一次。

我想要做的就是解析這個json,並生成html <ul><li>DeptName</li></ul>並將html放入div。

我GOOGLE了許多代碼,他們不工作。我認爲這可能是開始字符串「jsonDept」的問題。

任何人都可以爲此json編寫一個工作腳本嗎?謝謝!

回答

4

返回的對象包含一個屬性,即jsonDept。它是包含部門信息數組的jsonDept屬性。

function loadDepartmentList() { 
    $.ajax({ 
     url: "QueryDepartment.ashx", 
     //data: "", 
     type: "GET", 
     dataType: 'json', 
     success: function (data) { 
      // how to read json here? this is not working 
      $.each(data.jsonDept, function() { 
       alert("Name: " + this.DeptName); 
      }); 
     } 
    }) 
} 
+1

也許增加一個解釋爲OP爲什麼你使用'data.jsonDept:

爲UL

<ul id="list"></ul> 

功能創建ID ',即使我們有些人明白這一點 – Ian

0

這是你想解析json數組進入HTML列表「ul li DeptName/li/ul」嗎?

 function loadDepartmentList() { 
     $.ajax({ 
      url: "QueryDepartment.ashx", 
      //data: "", 
      type: "GET", 
      dataType: 'json', 
      success: function (data) {    
      $.each(data.jsonDept, function() { 
       $('#lsit').append('<li>'+this.DeptName+'</li>'); 
      }); 
     } 
    }) 
    } 

希望這會給一些想法..