gpt4 book ai didi

javascript - 解析 JSON 中的特定值以进行 ajax

转载 作者:行者123 更新时间:2023-11-28 02:57:04 24 4
gpt4 key购买 nike

我之前得到了这段代码,但我很难解析正确的数据。

我有以下 JSON

{
flavors: [{
"image": "images/bbtv.jpg",
"desc": "BioBusiness.TV",
"id": "1"
}, {
"image": "images/grow.jpg",
"desc": "Grow Staffing",
"id": "2"
}]
}

我只想显示 id:1 或 id:2。

我有以下 Ajax 代码

$.ajax({
type: "POST",
url: "foodservice/all.js",
dataType: "json",
cache: false,
data: {"flavors": filterId(flavors, 'a')},
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i,item){
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});

以及以下函数来过滤 JSON 对象

function filterId(obj, filteredId) {
var resultObj = $.extend({},obj);

for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].id && obj[i].id !== filteredId ) {
delete obj[i];
}
}
}
return resultObj;
}

但是,此代码不会返回任何内容。有人可以告诉我我错过了什么吗?

我对 JSON、Ajax 还很陌生,因此我们将不胜感激。

谢谢!

最佳答案

为什么不只检查“每个”代码?

  $.each(data.flavors, function(i,item){
if (item.id > 2) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});

关于javascript - 解析 JSON 中的特定值以进行 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2347709/

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