Jquery, looping over a json array
I am getting the following JSON string from a webservic开发者_JAVA百科e.
[{"TITLE":"asdasdasd","DESCRIPTION":"asdasd","PORTFOLIOID":1},
{"TITLE":"sss","DESCRIPTION":"sss","PORTFOLIOID":2},
{"TITLE":"sdfsdf","DESCRIPTION":"sdfsfsdf","PORTFOLIOID":3}]
Can i loop over this array in jquery and output the individual key/value pairs?
var a = [{"TITLE":"asdasdasd","DESCRIPTION":"asdasd","PORTFOLIOID":1}, ....]
$(a).each(function(index)
{
//this is the object in the array, index is the index of the object in the array
alert(this.TITLE + ' ' this.DESCRIPTION)
});
Check out the jQuery docs for more info... http://api.jquery.com/jQuery.each/
Absolutely. Assuming you're telling jQuery to evaluate this response as JSON with the AJAX methods, you'd simply do this:
<script>
$(data).each(function(idx, obj) //this loops the array
{
$(obj).each(function(key, value) //this loops the attributes of the object
{
console.log(key + ": " + value);
}
}
</script>
精彩评论