2012-08-30 70 views
1

我使用$ .post()檢索json結果,我希望能夠打印到每個結果的列表中。通過json結果循環創建列表

使用僅以下顯示最後JSON項目

JQUERY

$.post('/assets/inc/account-info.php', qString, function (data) { 
    console.log(data); 
    var datas = jQuery.parseJSON(data); 
    console.log(datas); 
    $("#note").append("<li>id=recordsarray_"+datas.id+"><a href='#"+datas.id+"'>"+datas.name+"</a></li>"); 
}); 
+1

請張貼你的數據變量的內容 – kannix

回答

2

我假設你得到對象的數組中的前端和該對象所具有的ID和姓名吧:

// To put data directly in html you can do this : 
    $.each(datas,function(i,data){ 
     $("#note").append("<li>id=recordsarray_"+data.id+"><a href='#"+data.id+"'>"+data.name+"</a></li>"); 
    }); 

OR 

// To Put your data in array you can do this : 
    var arr = []; 
    // This will help you putting the json object in to array 
    $.each(datas,function(i,data){ 
     arr.push({id:data.id, name:data.name}); 
    }); 

    // once you get the array you can loop through it and add it to your html: 
    for (i=0;i<arr.length;i++){ 
     $("#note").append("<li>id=recordsarray_"+arr[i].id+"><a href='#"+arr[i].id+"'>"+arr[i].name+"</a></li>"); 
    }); 
    } 
1

循環通過索引的數據和設置,那麼搶每一個的ID &名。 我還假設(自從你說的名單),你有多個級別的數據。

$.each(datas, function() { 
    $.each(this, function(key, value) { 
     $("#note").append("<li id=recordsarray_" + 
      datas[key].id + "><a href='#" + 
      datas[key].id + "'>" + 
      datas[key].name + "</a></li>" 
     ); 
    }); 
}); 
+0

原因爲-1? –

1
$(datas).each(function(){ $("#note").append("<li>id=recordsarray_"+this.id+"><a href='#"+this.id+"'>"+this.name+"</a></li>"); }); 
+1

這將工作?我以爲你必須使用$ .each函數,因爲這些不是jQuery對象? –

+0

它完美的工作 – ngplayground

0

試一下這個

$.each(datas, function(i,item){ 
    $("#note").append("<li>id=recordsarray_"+datas[i].id+"><a href='#"+datas[i].id+"'>"+datas[i].name+"</a></li>"); 
});