尝试根据类别获取子类别。 这是我从服务器得到的响应:
[{"id":"1","agname":"xxxx","sim":"xxxxxxxx","del":"0","coorid":"x"}]
现在,当我尝试在选择中显示它时,我得到未定义的输出,如下所示:
PS。我对 JavaScript 不太熟悉。这是我的代码:
$.post("getagents.php", {
coorid: coorid,
}, function(data){
console.log(data);
$('#agents').empty();
$.each(JSON.parse(data, function(index, subAgentObj){
$('#agents').append('<option value="'+subAgentObj.agname+'">'+subAgentObj.agname+'</option>');
}))
});
根据@Casper的回答,这就是我现在得到的。
最佳答案
$.each
方法旨在运行 all elements 。在这种情况下,您需要循环遍历数组,因此使用 JavaScript forEach
方法而不是 jQuery $.each
方法。
var response = '[{"id":"1","agname":"xxxx","sim":"xxxxxxxx","del":"0","coorid":"x"}]';
JSON.parse(response).forEach((item) => {
console.log(`id: ${item.id}`)
console.log(`agname: ${item.agname}`)
console.log(`sim: ${item.sim}`)
})
关于javascript - 未定义 foreach 作为 AJAX 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371353/