开发者

jquery each with json object

开发者 https://www.devze.com 2023-01-27 03:37 出处:网络
i have this json response: [{ \"i\": 39, \"id\": \"15399\" }, { \"i\": 38, \"id\": \"15386\" }, { \"i\": 37, \"id\": \"15329\"

i have this json response:

[{
    "i": 39,
    "id": "15399"
},
{
    "i": 38,
    "id": "15386"
},
{
    "i": 37,
    "id": "15329"
}]

now i need to put these elements in a html list. how can i use $.each to do that?

(something like:


  • 39: 15399
  • 38: 15386
  • etc...)

    (btw. i have no access to the file that gen开发者_JS百科erates the json code)


    Just iterate over your array, for example:

    var list = $("#myList");
    $.each(data, function(i, obj) {
      $("<li />", { text: obj.i + ": " + obj.id }).appendTo(list);
    });
    

    In a $.each() callback, you get the index and the object as parameters, in this case you just want to use the i and id properties off that. The alternative is just a ordinary for loop, like this:

    var list = $("#myList");
    for(var i=0, l=data.length; i<l; i++) {
      var obj = data[i];
      $("<li />", { text: obj.i + ": " + obj.id }).appendTo(list);
    });
    


    No need, it is just a javascript array - you can just use a for loop...

    for(var idx=0;idx<JSONResponse.length;idx++){
        var elem=JSONResponse[idx];
        $('ul#somewhere').append('<li>'+elem.i+': '+elem.id+'</li>');
    }
    
    0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消