jQuery / Ajax:如何作为Ajax成功函数的一部分循环遍历数组

时间:2015-07-20 11:06:46

标签: jquery arrays ajax loops

我有一个 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"
}

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

似乎你的数组没有正确解析

发送回复之前从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);
        });
    }
});

参考:http://api.jquery.com/jquery.parsejson/

答案 1 :(得分:1)

您需要将data变量中的字符串解析为对象:

success: function(data){
    console.log(data);  // for testing only
    var res=$.parseJSON(data);
    jQuery.each(res, function(index, value){
        console.log(value);
    });
}

您可以使用

var res=$.parseJSON(data)

或简单的JS:

var res=JSON.parse(data)

<强> Source