gpt4 book ai didi

javascript - $.getJSON 带有 for 循环,仅在调试时起作用

转载 作者:行者123 更新时间:2023-12-03 06:04:31 25 4
gpt4 key购买 nike

**我真的需要帮助,因为我无法找到可行的解决方案或自己完成。问题是,我无法获取信息。 “数据”应包括23个对象。问题是,在调试时一切正常。请帮我!!!我快要完蛋了。和回调或 then.(function...) 对我不起作用...;( **

function query_day2day(DateArray_){

var Fluid_id = 0;
var data_list = new Array();

//read out the select element
var e = document.getElementById("select_fluid");
var Fluid_id = e.options[e.selectedIndex].value;
//read in date
//var d = document.getElementById("datepicker");
//var date = d.value;
var dateArray = new Array();
dateArray = DateArray_;
//Bring the date array in the correct form to submit
for(i = 0; i<dateArray.length; i++)
{
var year = dateArray[i].substring(6, 10); //substring(start, end)
var month = dateArray[i].substring(0, 2);
var day = dateArray[i].substring(3, 5);

dateArray[i] = year + "-" + month + "-" + day;
//alert(dateArray[i]);
}

for(i = 0; i<dateArray.length; i++)
{
switch (Fluid_id) {
case '1':
$.getJSON(setAddress_Event() + 'liter_hour/' + Fluid_id + '/' + dateArray[i], function(data){


//data_callback(data, i); //I don´t understand this concept ;(
data_list[i] = data;


});
break;
case '2':
$.getJSON

已更新

        function getData(setAddress_Event, liter_hour, Fluid_id, dateArray){
return $.getJSON(setAddress_Event + liter_hour + Fluid_id + "/" + dateArray).then(function(data){
return {
data_list:data
}
});
}

for(var j = 0; j<dateArray.length; j++)
{
getData(setAddress_Event(), "liter_hour/", Fluid_id, dateArray[j]).then(function(returndata){
//received data!
alert(j);
data_collection[j] = returndata;

});

}


alert(data_collection); //Hier ist data_list undefined und beim returnen wird es richtig übergeben.... ohne diesem alert wird falsch übergeben.... dreck
return data_collection;

请帮助我,我需要所有数据而不仅仅是最后一个数据。调试正常,我不知道问题出在哪里......

Debugg Snippet

最佳答案

这是因为您在检索 JSON 的 Ajax 请求发回响应之前访问数据。请注意,当您执行时

    getData(setAddress_Event(), "liter_hour/", Fluid_id, dateArray[j]).then(function(returndata){
//received data!
alert(j);
data_collection[j] = returndata;
});

...内部函数未执行。它仅传递给 getData,并且您的代码会立即继续。只有当执行到脚本末尾时,Ajax请求才会一一调用你的回调函数,所以它们都会在主脚本结束后执行。

以下是处理该问题的方法(引入变量numPendingResults):

var numPendingResults = dateArray.length;
for(let j = 0; j<dateArray.length; j++) {
getData(setAddress_Event(), "liter_hour/", Fluid_id,
dateArray[j]).then(function(returndata){
//received data!
data_collection[j] = returndata;
numPendingResults--; // one less to wait for!
if (!numPendingResults) { // we have everything!
console.log(data_collection);
// anything you want to do with data_collection should be done here
// ...
// or call a function that will deal with it, from here.
}
});
}

您无法返回data_collection。相反,您应该调用如上所述的函数。该函数可能可以作为最外层函数的参数传递。或者进一步使用 Promise 系统。由您决定...

关于javascript - $.getJSON 带有 for 循环,仅在调试时起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39616771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com