如何正确传递 JQuery 延迟参数?

How to pass JQuery deferred paramaters correctly?

这是我的 jQuery 代码。我基本上是根据 IP 获取一些坐标,然后检索该位置的一些记录。我遇到的问题是从第一个 ajax 调用中检索到的参数对第二个 ajax 调用不可用。我是 deferred 的新手,真的不明白为什么这不起作用?我在代码中留下了一些评论作为问题以及问题所在。完整的答案将解释我所缺少的内容及其重要性。我正在努力解决这个问题,以使我的代码比嵌套调用更清晰。

$(document).ready(function() {
  $('#button').on('click', function() {
    //if the first call is successful then run the second function
    //is done the correct thing to use here?
    getLocation().done(getRecords);
  });
  //this works fine as i get the coordinates
  function getLocation() {
    return $.ajax({
      dataType: "json",
      url: 'http://ipinfo.io/json',
      success: function(response) {
        var coordinates = response.loc.split(',');
        return coordinates;
      }
    });
  }

  function getRecords(coordinates) {
   return $.ajax({
      dataType: "json",
      url: 'some url',
      data: {
        //this does not work as coordinates are undefined
        lat : coordinates[0],
        lon : coordinates[1],
      },
      success: function(response) {
        //do more stuff
      }
    });
  }

});

你的函数调用是落后的。尝试:

getRecords(getLocation());

要使这项工作如您所愿,您需要删除 success: 并改为使用 .then,以便您可以将值传递给链中的下一个承诺。

function getLocation() {
  return $.ajax({
    dataType: "json",
    url: 'http://ipinfo.io/json'/*,
    success: function(response) {
      var coordinates = response.loc.split(',');
      return coordinates;
    }*/
  }).then(function (response) {
    var coordinates = response.loc.split(',');
    return coordinates;
  });
}

您的问题是 success 处理程序的结果未传递给 done 处理程序。原来的response通过了。你可能想要 then.

不过,绝对没有理由在 2016 中使用 jQuery。