jQuery $ .post函数中.等待回调定义返回. [英] JQuery $.post in a function. Wait for callback to define the return.

查看:422
本文介绍了jQuery $ .post函数中.等待回调定义返回.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would I, using $.post() in a function, force the return on the post callback?

示例:

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

我尝试使用.done()和.queue()尝试使用它,但是都没有对我有用. 我了解我的示例存在根本缺陷;这样说,我如何实现我想要的功能?

I have tried playing around with it using .done() and .queue() however neither has worked for me. I understand there is a fundamental flaw in my example; with that said, how can I achieve my desired functionality?

推荐答案

这是不可能的. $ .Ajax调用将始终立即返回.当通过回调(可能是几秒钟后)调用返回时,您需要处理该返回.对于给定的调用,JavaScript永远不会阻塞.像这样考虑您的代码可能会有所帮助:

This is impossible. $.Ajax calls will always return immediately. You need to deal with the return when it is called through a callback (possibly several seconds later). Javascript never blocks for a given call. It may help to think of your code like this:

 //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演示文稿讨论了其优点在于细节.

If you're interested more on the benefits (and drawbacks) of Javascript's no-blocking, only callbacks: this Node.js presentation discusses its merits in excruciating detail.

这篇关于jQuery $ .post函数中.等待回调定义返回.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆