如何在进一步执行js之前从循环内部收集$ .get的所有结果

时间:2018-01-10 04:30:13

标签: javascript php jquery

我有一个循环的js,在循环中它出来从php脚本中获取值。

如何在脚本执行之前收集所有值?

我现在拥有的:

for(var i=0; i<TabelArray.length; i++) {
  $.get({
        url: drawURL + '/tabelPrice&name=' + name + '&width='+ width + '&height=' + height,
    dataType: 'json',
    success: function(data) {
        //console.log("succes");
        console.log(data);
    }, 
    error: function() {
       callback(false);
    }
    });
}
console.log("after loop");

打印出来: &#34;循环后#34; &#34;值1&#34; &#34;值2&#34;

我怀疑/需要的地方: &#34;值1&#34; &#34;值2&#34; &#34;循环后#34;

1 个答案:

答案 0 :(得分:1)

你必须等到所有回叫都回来,使用回调:

var results = [];

var after_loop = function () {
  console.log("after loop");
  // do whatever you want with results
};

var process_data_ok = function (data) {
  console.log(data);

  results.push(data);
  if ( results.length == TabelArray.length ) {
    after_loop();
  }
};

var process_data_fail = function () {
  console.log(false);

  results.push(false);
  if ( results.length == TabelArray.length ) {
    after_loop();
  }
};

for(var i=0; i<TabelArray.length; i++) {
  $.get({
    url: drawURL + '/tabelPrice&name=' + name + '&width='+ width + '&height=' + height,
    dataType: 'json',
    success: process_data_ok, 
    error: process_data_fail
  });
}
相关问题