如何循环JSON响应并插入不同的元素

时间:2013-08-31 01:39:15

标签: javascript jquery json

我的javascript知识非常有限..我很感激任何建议.. 我查看过以前的JSON问题和答案,但没有看到任何类似的内容。

我正在使用jQuery。我有以下格式的JSON服务器响应:

{
  "aNumBids_1": "4",
  "aHighBid_1": "100.00",
  "aBidAmount_1": "110.00",
  "aBidEnd_1": "09/27/2013 17:00",
  "aNumBids_2": "42",
  "aHighBid_2": "1,210.00",
  "aBidAmount_2": "1,260.00",
  "aBidEnd_2": "09/27/2013 17:01",
  "aNumBids_3": "12",
  "aHighBid_3": "1,100.00",
  "aBidAmount_3": "1,150.00",
  "aBidEnd_3": "09/27/2013 17:02",
  "aNumBids_4": "26",
  "aHighBid_4": "1,460.00",
  "aBidAmount_4": "1,510.00",
  "aBidEnd_4": "09/27/2013 17:03",
  "aNumBids_5": "32",
  "aHighBid_5": "1,210.00",
  "aBidAmount_5": "1,260.00",
  "aBidEnd_5": "09/27/2013 17:04"
}

每对的第一个元素是页面上的元素名称(name='aBidAmount_5')。每对中的第二个元素是要放入该元素的内容。

如何循环浏览此json响应?

我已经走到这一步了:

AJAX.getPrice = function(){

  var request = $.ajax({
    url: serverScript,
    data: JSON.stringify(aItems) ,
    dataType: "json"
  });

  request.done(function() {
   // update the element value
    /* i'm lost here */
  });

  request.fail(function(jqXHR, textStatus) {
    // If console is available output the error to console log
    if (typeof console == "object") {
       console.log( "Request failed: " + textStatus +data );
    }
  });

}

3 个答案:

答案 0 :(得分:3)

假设“元素名称”是元素的id,这应该有效:

request.done(function(data) {
    for(var k in data) {
        if(data.hasOwnProperty(k)) {
            $('#'+k).html(data[k]);
        }
    }
});

答案 1 :(得分:1)

如果这些是输入名称,则在done回拨使用

request.done(function(data) {
   for(i in data) {
      $("input[name="+i+"]").val(data[i]);
   }
});

答案 2 :(得分:0)

Js Fiddle:http://jsfiddle.net/vuQLu/

JS:

var output = '<ul>';
$.each(data, function(key, value){

    $.each(value, function(key, value){
        output += '<li>' + key + ' => ' + value + '</li>';
    });

});
output += '</ul>';

$(".myClass").html(output);

HTML:

<div class="myClass"> </div>