你好,我有使用php的输出
[{“ date”:“ 2019-02-10”,“ pleads”:1},{“ date”:“ 2019-02-12”,“ pleads”:1},{“ date”:“ 2019-02-14“,” pleads“:1}]
我可以通过此Jquery代码轻松访问
// AJAX Request to get the data by UserID and Week 1
$.get('/dashboard/performance?name=' + document.getElementById('agents').value + '&week=0', function(data){
$.each(data,function(i,value){
var tr =$("<tr/>");
tr.append($("<th/>",{
text : value.date
})).append($("<th/>",{
text : value.pleads
}))
$('#tableData-performance-week1').append(tr);
})
});
但是由于我必须进行一些修改才能从db返回多个数据,因此php返回的是这个
{“ adminleads”:[{“ date”:“ 2019-02-02”,“ aleads”:1}],“ managerleads”:[{“ date”:“ 2019-02-01”,“ mleads “:1}],” personalleads“:[{” date“:” 2019-02-02“,” pleads“:2},{” date“:” 2019-02-03“,” pleads“:1} ,{“ date”:“ 2019-02-04”,“ pleads”:1},{“ date”:“ 2019-02-05”,“ pleads”:1},{“ date”:“ 2019-02 -06“,” pleads“:1}]}
我如何通过JQuery访问它们?因为我尝试了,但我无法以正常方式访问它们
答案 0 :(得分:0)
在这种情况下,jQuery.each
也将与对象一起使用,第一个参数将是属性名称,第二个参数将是属性值。
现在,您必须遍历数组(内部数组,属性值),并为此使用Array#forEach
方法,并在循环中检查是否定义了plead
属性,然后创建并附加{ {1}}。要检查是否定义了属性,可以使用in
operator。
tr
// iterate over all values
$.each(data, function(k, arr) {
// iterate over all objects within array
arr.forEach(function(value) {
// check pleads property defined if defined
// do the rest as you did early
if ('pleads' in value) {
var tr = $("<tr/>");
tr.append($("<th/>", {
text: value.date
})).append($("<th/>", {
text: value.pleads
}))
$('#tableData-performance-week1').append(tr);
}
});
})
var data = {
"adminleads": [{
"date": "2019-02-02",
"aleads": 1
}],
"managerleads": [{
"date": "2019-02-01",
"mleads": 1
}],
"personalleads": [{
"date": "2019-02-02",
"pleads": 2
}, {
"date": "2019-02-03",
"pleads": 1
}, {
"date": "2019-02-04",
"pleads": 1
}, {
"date": "2019-02-05",
"pleads": 1
}, {
"date": "2019-02-06",
"pleads": 1
}]
}
$.each(data, function(k, arr) {
arr.forEach(function(value) {
if ('pleads' in value) {
var tr = $("<tr/>");
tr.append($("<th/>", {
text: value.date
})).append($("<th/>", {
text: value.pleads
}))
$('#tableData-performance-week1').append(tr);
}
});
})