当json数据在数组中时如何在div中显示json数据
"data": [ { "name": "Rehan", "location": "Pune", "description": "hello hi", "created_by": 13692, "users_name": "xyz", }, { "name": "Sameer", "location": "Bangalore", "description": "how are you", "created_by": 13543, "users_name": "abc", },
API包含100多个数据,因此我们如何在html页面中显示这些数据。 像这样:
Name: Rehan location: Pune Description: hello hi created by: 13692 user name: xyz
这个怎么样?
var data = [ { "name": "Rehan", "location": "Pune", "description": "hello hi", "created_by": 13692, "users_name": "xyz", }, { "name": "Sameer", "location": "Bangalore", "description": "how are you", "created_by": 13543, "users_name": "abc", }, ] var htmlText = ''; for ( var key in data ) { htmlText += ''; htmlText += ' Name: ' + data[key].name + '
'; htmlText += ' Location: ' + data[key].location + '
'; htmlText += ' Description: ' + data[key].description + '
'; htmlText += ' Created by: ' + data[key].created_by + '
'; htmlText += ' Username: ' + data[key].users_name + '
'; htmlText += ''; } $('body').append(htmlText);
这将输出到:
Name: Rehan Location: Pune Description: hello hi Created by: 13692 Username: xyz Name: Sameer Location: Bangalore Description: how are you Created by: 13543 Username: abc
假设你有一个id为#table
的表,循环遍历json对象并为每个对象项附加一行:
var jsonObj = { ... } for (i in jsonObj) { for (n in jsonObj[i]) { $('#table > tbody').append('' + n + ' ' + jsonObj[i][n] + ' '); } }
var data = [ { "name": "Rehan", "location": "Pune", "description": "hello hi", "created_by": 13692, "users_name": "xyz", }, { "name": "Sameer", "location": "Bangalore", "description": "how are you", "created_by": 13543, "users_name": "abc", }]; for (i=0;i<=data.length;i++) { for (n in data[i]) { $('#table > tbody').append('' + n + ' ' + data[i][n] + ' '); } }
试试这个:
小提琴: http : //jsfiddle.net/Sourabh_/1m2tjth3/
您可以根据您的要求进行修改。