2012-06-27 39 views
2

我正在遍歷我的JSON響應。我已經有了id爲id的HTML元素作爲參數名稱。迭代槽JSON數組:獲取參數的名稱

例如,我的JSON響應包含一個"costcenter":"1234",並且有一個<span>元素,其ID爲costcenter

現在,我沒有爲每個id寫一個語句,而是我可以迭代通過JSON數組,並自動讀取它的名字。

這是我得到

$(".dataset").click(function() { 
    changeid = this.id; 

    $.ajax({ 
     url: "source", 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     data: { 
      id: changeid 
     }, 
     success: function(data) { 
      // How to get the name of the parameter, and then read it's value? 
     } 
    }) 
}) 

的JSON看起來像,它只是一個維度和1次的結果只設置: {"changeid":"1","costcenter":"478","manager":"John Smith"}

+0

你的代碼不檢查每個.dataset元素 –

+0

@cristi_b你爲什麼這麼想? – Ahatius

回答

3

如果我理解你的問題,你想在這樣的事情你成功功能:

for (var key in data) { 
    $('#'+key).html(data[key]); 
} 
+0

是的,你說得對。像一個迷人的工作! – Ahatius