jQuery/Ajax : How to loop through array as part of Ajax success function

标签 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"
}

提前非常感谢您的帮助。

最佳答案

似乎您的数组未正确解析

在发送响应之前从 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/

关于jQuery/Ajax : How to loop through array as part of Ajax success function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514909/

相关文章:

arrays - 在Lua中寻址数组中的索引

javascript - 我需要一个系统来发布 JavaScript 游戏的高分,但它必须很难被愚弄

javascript - 固定状态栏与滑出菜单冲突

javascript - 删除之前通过 jQuery 添加的类

ruby - 根据字典匹配和替换 Ruby 数组

javascript - 尝试在 javascript 中使用循环时出错,获取 "undefined"

javascript - 无法使用 jquery/ajax/json 从 mysql 获取数据以选择框

c# - ASP.NET 可视化 Web 部件 + AJAX,无法使其正常工作

javascript - 使用 Jquery 的 AJAX 无法跨 JSP 页面工作

javascript - Highcharts 无法访问 z 值