在存储数组时丢失Ajax调用的结果数据

时间:2017-10-30 05:56:52

标签: javascript arrays ajax

我有以下代码,我正在进行Ajax调用以获取数据。在成功函数中,我创建了一个数组(它们是全局声明的)。

for (var i=0; i< arrayOf_ID.length;i++) {  
    $.ajax({
        type: "GET",
        url: 'URL' +arrayOf_ID[i],
        dataType: 'json',
        contentType: false,
        async: false,
        cache: false,
        processData: false,
        success: function (result) {
            for(var i=0; i<result.length; i++)
            {
                if(result[i].Comments!="")
                {
                    section[i]=result[i].section;
                    Comment[i]= result[i].Comments;
                    checklist[i]= result[i].checklist;
                }
            }      
        },
        error: function (error) {
            alert("");
        }
    });    
}

工作正常,完全没有错误。但我的问题是我在创建数组时丢失了数据。我完全得到了ajax调用的结果,但是在数组中我得到的只是最后一个id的值。

让我们说:arrayOf_ID有4个值(4只是一个例子,它可以有50+个值)我正在按照每个ID创建URL,如上所示,我想要数组(Section,Comment,所有4个ID的清单一起,但我得到的结果只有最后一个ID(arrayOf_ID)的数组(Section,Comment,checklist)。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

for (var i = 0; i < result.length; i++) {
            if (result[i].Comments != "") {
                section[i] = result[i].section;
                Comment[i] = result[i].Comments;
                checklist[i] = result[i].checklist;
            }
        }

而不是以这种方式使用section [i] = result [i] .section而不是覆盖你应该使用

for (var i = 0; i < result.length; i++) {
       if (result[i].Comments != "") {
          section.push(result[i].section)
          Comment.push(result[i].Comments)
          checklist.push(result[i].checklist)
     }
  }

答案 1 :(得分:0)

您正在覆盖此循环中的值:

        for (var i = 0; i < result.length; i++) {
            if (result[i].Comments != "") {
                section[i] = result[i].section;
                Comment[i] = result[i].Comments;
                checklist[i] = result[i].checklist;
            }
        }

所有三个变量中的当前值,即section,Comment,checklist都被下一次迭代覆盖,因此在循环结束时,您将获得最后的迭代值。更好的方法是使用Object并将值存储在由唯一标识符或关键字区分的键中。结构可以是:

var Obj = {
        1: {
            section: [...],
            checklist: [...],
            Comments: [...]
        },2: {
            section: [...],
            checklist: [...],
            Comments: [...]
        },3: {
            section: [...],
            checklist: [...],
            Comments: [...]
        },4: {
            section: [...],
            checklist: [...],
            Comments: [...]
        }
        ....
    }