简体   繁体   English

与$ .get一起使用循环时,如何在循环外获取数据

[英]How can I get data outside the loop when using loop with $.get

I'm very new at Javascript. 我是Java语言的新手。 I had some issue going on with my script I had to loop through $.get and I stuck in a loop here is my code 我的脚本遇到了一些问题,我不得不遍历$ .get,而我陷入了一个循环,这是我的代码

a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]

    for (var i = 0; i < a.length; i+=1){
       .$get('url' + "?params=" + a[i],function(data2){             
           school = data2['data']; 
        });
    }

    console.log(school);

When I tried to console.log(school) it keeps showing "object{}" 当我尝试console.log(school)时,它一直显示“ object {}”

How can I get the data outside loop? 如何获取循环外的数据?

I would be really grateful if you can help me with this issue. 如果您能帮助我解决这个问题,我将不胜感激。

Thanks. 谢谢。

you must use the callback function or something like this. 您必须使用回调函数或类似的东西。

because the $.get is async function and when 因为$ .get是异步函数,何时

console.log(school);

execute(!) the school is not evaluated yet. execute(!)学校尚未评估。

you can use some things like this. 您可以使用诸如此类的东西。

    a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]

    for (var i = 0; i < a.length; i+=1){
       .$get('url' + "?params=" + a[i],function(data2){             
           school = data2['data']; 
           console.log(school);
        });
    }

or 要么

a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]
var  school ={};
for (var i = 0; i < a.length; i+=1){
   .$get('url' + "?params=" + a[i],function(data2){             
       school = data2['data']; 
       whenitready();
    });
}

function whenitready(){
   console.log(school);
}

If you need to wait until all your requests are done, you need something like this: 如果您需要等到所有请求都完成后,就需要这样的东西:

var endpoints = [];
for (var i = 0; i < a.length; i+=1) {
  endpoints.push($.get('url' + '?params=' + a[i]));
}
$.when.apply($, endpoints).done(function () {
  // Function arguments array differs if we have one or more than one endpoint.
  // When called with one endpoint arguments is an array of three elements [data, textStatus, jqXHR].
  // When called with more than one endpoint arguments is an array of arrays [[data, textStatus, jqXHR], ...].
  // Normalize the single endpoint to the generic list one.
  var args = endpoints.length > 1 ? arguments : [arguments];
  for (var i = 0; i < args.length; i++) {
    var data = args[i][0];
    // Do stuff here with every data received...
    school = ... 
  }

  console.log(school);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM