jQuery/Ajax:如何遍历数组作为Ajax成功函数的一部分 [英] jQuery / Ajax: How to loop through array as part of Ajax success function

查看:77
本文介绍了jQuery/Ajax:如何遍历数组作为Ajax成功函数的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Ajax调用,该调用返回一个数组,并且需要对该数组中的每个值进行处理.

I have an Ajax call that returns an array and need to do something with each of the values from this array.

到目前为止,我有以下内容,但这将返回以下错误:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in array(5)...

有人可以告诉我我在这里做错了吗.我该如何使用每个值?

Can someone tell me what I am doing wrong here resp. how I can do something with each of the values ?

我的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);
        });
    }
});

数据"示例(来自控制台日志):

Example for "data" (from console log):

array(5) {
  [1]=>
  string(6) "Value1"
  [2]=>
  string(6) "Value2"
  [3]=>
  string(6) "Value3"
  [4]=>
  string(6) "Value4"
  [5]=>
  string(6) "Value5"
}

在此先感谢您的帮助.

Many thanks in advance for any help.

推荐答案

好像您的数组无法正确解析

seems like your array not parsed properly

从php端发送响应之前

from php side before sending response

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:如何遍历数组作为Ajax成功函数的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆