这是我的功能
function getRecords(){
$.getJSON( "viewcustomers.php", function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<td>" + val + "</td>" );
alert(items);
});
});
}
viewcustomers.php中的数据如下:
[{"id":"1","name":"ali","cnic":"01","address":"nipa","email":"301","phone":"luxairy "},{"id":"2","name":"raheel","cnic":"1234567","address":"abc flat","email":"raheel@gmail.com","phone":"0342"},{"id":"5","name":"Raheel","cnic":"123-4567-45","address":"Gulshan block 13-c","email":"raheel@gmail.com","phone":"03422301775"},{"id":"4","name":"zain","cnic":"12345678","address":"f.b area","email":"zain@gmail.com","phone":"7894561"},{"id":"6","name":"Raheel","cnic":"123-4567-45","address":"Gulshan block 13-c","email":"raheel@gmail.com","phone":"03422301775"},{"id":"7","name":"Ali","cnic":"123456786","address":"nipa","email":"ali@gmail.com","phone":"1234568"},{"id":"8","name":"Waqas","cnic":"123456748","address":"F.b area","email":"waqas@gmail.com","phone":"1234568"},{"id":"9","name":"Owais","cnic":"1234567","address":"Fb area","email":"owais@gmail.com","phone":"12345678"}]
但是当我运行我的jquery函数时,它给了我[object Object]而不是上面的键值。
答案 0 :(得分:4)
在您的情况下,item
实际上是array
。而你正在从JSON中推动其中的值。所以为了以字符串格式查看它,
你必须使用,
alert(JSON.stringify(items));
在深入了解您的JSON时,您正在遍历每个对象,因此您应该在插入数组时对这些对象进行字符串化,例如,
items.push( "<td>" + JSON.stringify(val) + "</td>" );
答案 1 :(得分:3)
因为对象的to字符串实现返回[object Object]
,所以您可以使用JSON.stringify()来处理此问题。对于旧浏览器,您必须包含json2
items.push( "<td>" + JSON.stringify(val) + "</td>" );
演示:Fiddle - 查看浏览器控制台
<强>更新强>
如果您使用.map()
,应该很简单var items = $.map(data, function (obj) {
return "<tr>" + $.map(obj, function (val) {
return '<td>' + val + '</td>'
}).join('') + "</tr>";
});
console.log(items.join(''));
演示:Fiddle