【问题标题】:AJAX - Wait for data to append before looping nextAJAX - 在循环下一个之前等待数据附加
【发布时间】:2016-08-04 08:28:35
【问题描述】:

我正在用 JavaScript 创建一个下拉列表,我正在通过 Ajax 和 JSON 加载数据,此时我的代码循环通过一组部门并在每次迭代中运行到 ajax 调用。

我的问题是我的数据似乎是按随机顺序附加的,很可能是按照加载速度最快的顺序加载。

我希望能够循环通过我的 Ajax 调用并按照我声明的顺序(针对每个部门)附加数据。 这是可以做到的吗?

这是我的代码:

//-- Ajax --
var departments = ['Accounts', 'Commercial', 'Installation', 'Production', 'Sales'];
var i;

for (i = 0; i < departments.length; i++) {
    $.ajax({
        type: "POST",
        url: "Default.aspx/EmployeesDropDown",
        data: '{X: "' + departments[i] + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "text json",
        async: true,
        success: createdropdown,
        failure: function () {
            alert("FAIL!");
        }
    });
}


//-- Creates dropdown --
function createdropdown(data) {
...appends all the data to my drop down list...
  }

感谢任何帮助或建议,在此先感谢您。

编辑:这个问题与相关问题不同,因为我需要能够遍历字符串数组,而不是仅仅基于数字进行迭代。

【问题讨论】:

标签: javascript jquery ajax loops


【解决方案1】:

如果您想按照它们在 departments 数组中出现的顺序加载部门,您可以一个一个地加载它们,等待每个 ajax 请求完成,直到您开始下一个请求。

这是一个例子:

var departments = ['Accounts', 'Commercial', 'Installation', 'Production', 'Sales'];
var i = 0;

function reqDep(department) {

  /*
  Since i can't use ajax here let's use a promise.
  */

  var p = new Promise(function(res, rej) {
    setTimeout(function() {
      res(department)
    }, 1000)
  })
  return p;

  // This is what you would actually do.

  /*
  var data =  '{X: "' + department + '"}'
  return $.ajax({
    type: "POST",
    url: "Default.aspx/EmployeesDropDown",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "text json",
  });
  */  
}

function initDepartments(index) {
  reqDep(departments[index])
  // Here you would use `.done(function(data...`
  // I am using `.then(function(data...`
  // because of the promise.
  .then(function(data) {
    console.log(data)
    if(i < departments.length) {
      initDepartments(i)
    }
  })
  i++;
};

initDepartments(i)

【讨论】:

    猜你喜欢
    • 2021-02-15
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2014-07-06
    相关资源
    最近更新 更多