-4

我将如何在函数中使用 $.post() 强制返回 post 回调?

例子:

function myFunction(){
   $.post(postURL,mydata,function(data){
      return data; 
   });
}

我曾尝试使用 .done() 和 .queue() 来玩弄它,但它们都不适合我。我知道我的示例中有一个根本缺陷;话虽如此,我怎样才能实现我想要的功能?

4

2 回答 2

6

这是不可能的。$.Ajax 调用总是会立即返回。您需要在通过回调调用时处理返回(可能是几秒钟后)。Javascript 从不阻塞给定的调用。像这样考虑您的代码可能会有所帮助:

 //This entirely unrelated function will get called when the Ajax request completes
 var whenItsDone = function(data) {
   console.log("Got data " + data); //use the data to manipulate the page or other variables
   return data; //the return here won't be utilized
 }

 function myFunction(){
   $.post(postURL, mydata, whenItsDone);
 }

如果您对 Javascript 的无阻塞的优点(和缺点)更感兴趣,只有回调:这个Node.js 演示文稿讨论了它在令人痛苦的细节方面的优点。

于 2011-07-29T18:21:51.793 回答
0
function myFunction(){
   var deferred = new $.Deferred();

   var request = $.ajax({
      url: postURL,
      data: mydata
   });

   // These can simply be chained to the previous line: $.ajax().done().fail()
   request.done(function(data){ deferred.resolve(data) });
   request.fail(function(){ deferred.reject.apply(deferred, arguments) });

   // Return a Promise which we'll resolve after we get the async AJAX response.
   return deferred.promise();
}
于 2012-08-29T14:51:53.793 回答