递延和阿贾克斯 [英] Deferred and Ajax

查看:81
本文介绍了递延和阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样读取JSON服务:

Reading a JSON-Service like this:

$.ajax({
  url:'activeIDs',
  success : function(data){ // data = [14,15]
    var tableRows = [];
    for (var dataIndex=0; dataIndex < data.length; dataIndex++) {
      var isLast = dataIndex == (data.length - 1);
      $.ajax({
        url: 'info?id=' + data[dataIndex],
        success: function(data2) { // "foo", "bar"
          tableRows.push(data2.name);
          if (isLast) {
            alert(tableRows.length);
          }
        }
      });
    }
  }
});

第一个网络跟踪为:

  1. activeIDs = [14,15]
  2. info?id = 14(耗时2秒)= "foo"
  3. info?id = 15(耗时4秒)= "bar"
  1. activeIDs = [14,15]
  2. info?id=14 (takes 2 seconds) = "foo"
  3. info?id=15 (takes 4 seconds) = "bar"

在这种情况下,警报显示为"2".

In this case the alert gives "2".

第二个网络跟踪是不同的:

Seconds network-trace is different:

  1. activeIDs = [14,15];
  2. info?id = 14(需要20秒)= "foo"(现在需要很长时间)
  3. info?id = 15(耗时1秒)= "bar"
  1. activeIDs = [14,15];
  2. info?id=14 (takes 20 seconds) = "foo" (now takes very long)
  3. info?id=15 (takes 1 second) = "bar"

在这种情况下,警报在一秒钟后发出1,这是糟糕的!

In this case the alert gives 1 after one second, this is bad!!!

如何使用$ .Deferred代替isLast?

How to use $.Deferred instead of isLast?

推荐答案

alert ing之前,您需要等待所有请求完成.

You'll need to wait for all requests to finish before alerting.

$.ajax({
  url:'activeIDs',
  success : function(data){ // data = [14,15]
    var tableRows = [];
    var requests = [];
    for (var dataIndex=0; dataIndex < data.length; dataIndex++) {
      var isLast = dataIndex == data.length;

      var request = $.ajax({
        url: 'info?id=' + data[dataIndex]
      }).done(function(data2) { // "foo", "bar"
        tableRows.push(data2.name);
      });

      requests.push(request);
    }

    // wait for all requests to finish here
    $.when(requests).then(function(){
      // all success functions have been called and updated things appropriately
      alert(tableRows.length);
    }
  }
});

这假定所有请求都成功. 看起来也有一些错字

This assumes that all requests succeed. It also looks like there are a few typos

  • tableRows在哪里更新?
  • entries在哪里定义?
  • Where does tableRows get updated?
  • Where is entries defined?

修改 现在使用Promise样式成功处理程序.在调用$.when().then回调之前,应将结果推送到tableRows

Edit Now using promise style success handler. Should push the result in to tableRows before calling the $.when().then callback

这篇关于递延和阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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