【问题标题】:deferring return of $.getJSON with async set to false [duplicate]延迟返回 $.getJSON 并将异步设置为 false [重复]
【发布时间】:2018-02-09 18:40:50
【问题描述】:

我尝试了在其他问题中看到的各种解决方案,但没有成功记录 data.ip

当我登录foo 时,我只返回undefined。为什么在 async 设置为 false 时未记录 ip 属性?

TY

$.ajaxSetup({
  async: false
});

var getIp = function() {
  var ip;
  $.getJSON('//freegeoip.net/json/?callback=?', function(data) {
    ip = data.ip;
  });
  return ip;
}

var foo = getIp();
console.log(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【问题讨论】:

  • 请求的页面是否返回了有效的 JSON?
  • @Marcin:是的,从请求的页面返回了有效的 JSON。
  • 永远,永远,永远将 async 设置为 false。它会严重损害您网页的性能。
  • 不要使用async:false正确使用异步回调模式
  • $.getJSON 不接受 async: false 根据 stackoverflow.com/questions/2765411/…

标签: javascript jquery json ajax


【解决方案1】:

您没有正确实现 AJAX。我更改了您的函数,使其返回Promise(注意函数中的return 关键字)。然后在.then() 内部,您可以传递一个回调函数,该函数将在Ajax 完成后执行。$.getJSON()Ajax 的实现(http://api.jquery.com/jquery.ajax/

注意:

我强烈建议不要在任何xhr / Ajax 中使用async: false,因为它会降低您的网站速度。最好使用下面的代码:

var getIp = function() {
  var ip;
  return $.getJSON('//freegeoip.net/json/?callback=?', function(data) {
    return data.ip;
  });
}

getIp().then(function(res) {
  console.log(res);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • 编辑了答案
猜你喜欢
  • 2018-09-26
  • 2018-06-13
  • 1970-01-01
  • 2017-04-13
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
相关资源
最近更新 更多