如何正确传递 JQuery 延迟参数



这是我的jQuery代码。我基本上是根据IP抓取一些坐标,然后检索该位置的一些记录。我遇到的问题是从第一个 ajax 调用中检索到的参数对第二个 ajax 调用不可用。我是延期的新手,真的不明白为什么这不起作用?我在代码中留下了一些注释作为问题以及问题所在。一个完整的答案将解释我错过了什么以及为什么它很重要。我试图解决这个问题,以使我的代码更干净,而不是嵌套调用。

$(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
      }
    });
  }
});

为了使这项工作符合您的预期,您需要删除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。

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

getRecords(getLocation());

最新更新