gpt4 book ai didi

javascript - 使用 jQuery 从数据库访问对象

转载 作者:行者123 更新时间:2023-11-30 21:33:01 25 4
gpt4 key购买 nike

你好,我用 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 访问它们?因为我试过了,但我无法以正常方式访问它们,非常感谢

最佳答案

jQuery.each在这种情况下也将与对象一起使用,第一个参数将是属性名称,第二个参数将是属性值。

现在你必须遍历数组(内部数组,属性值)使用Array#forEach该方法和循环检查 plead 属性是否已定义,如果已定义,则创建并附加 tr。要检查属性是否已定义,您可以使用 in operator .

 // 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);
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableData-performance-week1"></table>

关于javascript - 使用 jQuery 从数据库访问对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55267757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com