我将如何在函数中使用$ .post()强制回调函数后回调?
例子:
function myFunction(){
$.post(postURL,mydata,function(data){
return data;
});
}
我曾尝试使用.done玩了()和.queue(),但是他们都没有为我工作。 我知道我的例子中存在一个根本缺陷;与那个说,我怎么能达到我想要的功能?
我将如何在函数中使用$ .post()强制回调函数后回调?
例子:
function myFunction(){
$.post(postURL,mydata,function(data){
return data;
});
}
我曾尝试使用.done玩了()和.queue(),但是他们都没有为我工作。 我知道我的例子中存在一个根本缺陷;与那个说,我怎么能达到我想要的功能?
这是不可能的。 $ .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 presentation讨论了难以忍受的细节它的优点。
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();
}
为什么你想这样做?您需要使用回调函数来处理返回的数据。 –
并且在处理完所述数据之后,我需要传回某些值。 – rlemon
您可能需要重构您的代码,因为没有好的方法来执行此操作。 –