【问题标题】:convert a async:false AJAX function into an $.Deferred one [duplicate]将 async:false AJAX 函数转换为 $.Deferred 函数 [重复]
【发布时间】:2018-11-19 13:20:00
【问题描述】:

我现在正在苦苦挣扎两天,试图将带有 async:false 的简单 AJAX 函数转换为一个不错的 jQuery Deferred() 函数。我试图返回 AJAX 响应的一切都不起作用:-(

这是我的旧(短)代码版本:

function uiText($textID) {
   var text = $.ajax({
     url: "uitext.php",
     async: false,
     success: function(response){}
   };
   return text.response;
}
console.log(uiText('foo'));  //shows me the response from uitext.php

我如何使用 $.Deferred 和/或 $.when().done() 来做到这一点

谢谢迈克

【问题讨论】:

标签: javascript jquery ajax jquery-deferred


【解决方案1】:

$.Deferred 和/或 $.when().done()

不要。那已经过时了。 $.ajax 返回一个承诺兼容的对象。

function uiText($textID) {
   const request = $.ajax({
     url: "uitext.php"
   });
   return request;
}

uiText('foo').then( response => console.log(response) );

【讨论】:

  • 我阅读了很多关于使用 promise 的内容,并且我已经在其他情况下使用了它。但在这种情况下,我需要 uiText 返回 ajax 响应......而不是 promise 对象。这可能吗?
  • @mikexmagic — 没有。$.Deferred$.when().done() 只是创建承诺的方式。
猜你喜欢
  • 2016-04-03
  • 1970-01-01
  • 2015-11-05
  • 2019-05-08
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
相关资源
最近更新 更多