我有一个Ajax 调用,它返回一个数组,并且需要对该数组中的每个值执行某些操作。
到目前为止,我有以下内容,但这会返回以下错误:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in array(5)...
有人可以告诉我我在这里做错了什么吗?我如何对每个值做一些事情?
我的 Ajax:
$.ajax({
type: "post",
url: "ajax.php",
cache: "false",
data: {
node: 'fetchValues',
itemIDs: itemIDs
},
success: function(data){
console.log(data); // for testing only
jQuery.each(data, function(index, value){
console.log(value);
});
}
});
“数据”示例(来自控制台日志):
array(5) {
[1]=>
string(6) "Value1"
[2]=>
string(6) "Value2"
[3]=>
string(6) "Value3"
[4]=>
string(6) "Value4"
[5]=>
string(6) "Value5"
}
提前非常感谢您的帮助。
最佳答案
似乎您的数组未正确解析
在发送响应之前从 php 端
echo json_encode($result); // REPLACE $result WITH YOUR OUTPUT ARRAY
在 jquery 端:
$.ajax({
type: "post",
url: "ajax.php",
dataType : 'JSON',
cache: "false",
data: {
node: 'fetchValues',
itemIDs: itemIDs
},
success: function(data){
console.log(data); // for testing only
var data=$.parseJSON(data);
jQuery.each(data, function(index, value){
console.log(value);
});
}
});
关于jQuery/Ajax : How to loop through array as part of Ajax success function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514909/