JavaScript:Ajax 请求后的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3222347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:44:35  来源:igfitidea点击:

JavaScript: Global variables after Ajax requests

javascriptjqueryajaxglobalsynchronous

提问by Gal

the question is fairly simple and technical:

这个问题相当简单和技术性:

var it_works = false;

$.post("some_file.php", '', function(data) {

     it_works = true;

});

alert(it_works); # false (yes, that 'alert' has to be here and not inside $.post itself)

What I want to achieve is:

我想要实现的是:

alert(it_works); # true

Is there a way to do that? If not can $.post()return a value to be applied to it_works?

有没有办法做到这一点?如果不能$.post()返回一个值来应用it_works

回答by gblazex

What you expect is the synchronous(blocking) type request.

您期望的是同步阻塞)类型的请求。

var it_works = false;

jQuery.ajax({
  type: "POST",
  url: 'some_file.php',
  success: function (data) {
    it_works = true;
  }, 
  async: false // <- this turns it into synchronous
});?

// Execution is BLOCKED until request finishes.

// it_works is available
alert(it_works);

Requests are asynchronous(non-blocking) by defaultwhich means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.

默认情况下,请求是异步的非阻塞),这意味着浏览器不会等待它们完成才能继续工作。这就是您的警报得到错误结果的原因。

Now, with jQuery.ajaxyou can optionally set the request to be synchronous, which means that the script will only continue to run afterthe request is finished.

现在,jQuery.ajax您可以选择将请求设置为同步,这意味着脚本只会在请求完成继续运行。



The RECOMMENDEDway, however, is to refactoryour code so that the data would be passed to a callbackfunction as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:

建议的方式,但是,是重构代码,以便数据将被传递到一个回调函数,一旦请求完成。这是首选,因为阻止执行意味着阻止 UI,这是不可接受的。这样做:

$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}

// All code here should be INDEPENDENT of the result of your AJAX request
// ...

Asynchronousprogramming is slightly more complicatedbecause the consequence of making a request is encapsulated in a function instead of following the request statement. Butthe realtime behavior that the user experiencescan be significantly betterbecause they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronousprogramming is disrespectfuland should not be employedin applications which are used by people.

异步编程稍微复杂一些,因为发出请求的结果被封装在一个函数中,而不是遵循请求语句。但是用户体验的实时行为可能会明显更好,因为他们不会看到缓慢的服务器或缓慢的网络导致浏览器表现得好像它已经崩溃。同步编程是不尊重的不应在人们使用的应用程序中使用。

Douglas Crockford(YUI Blog)

道格拉斯·克罗克福德YUI 博客

回答by mattbasta

AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.postout into the longer $.ajaxcall and adds the asyncoption).

AJAX 代表异步 JavaScript 和 XML。因此,对服务器的发布与函数的其余部分不同步。尝试一些这样的代码(它只是将速记$.post分解为更长的$.ajax调用并添加async选项)。

var it_works = false;

$.ajax({
  type: 'POST',
  async: false,
  url: "some_file.php",
  data: "",
  success: function() {it_works = true;}
});

alert(it_works);

Hope this helps!

希望这可以帮助!

回答by Hosam Aly

It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.

看来你的问题只是一个并发问题。post 函数接受一个回调参数来告诉您发布何时完成。您不能像这样在全局范围内发出警报并期望帖子已经完成。您必须将其移动到回调函数中。

回答by Jesse Dhillon

The reason your code fails is because post()will start an asynchronousrequest to the server. What that means for you is that post()returns immediately, notafter the request completes, like you are expecting.

您的代码失败的原因是post()将向服务器发起异步请求。这对您来说意味着post()立即返回,而不是像您期望的那样在请求完成后返回。

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

那么,您需要的是同步请求并阻塞当前线程,直到请求完成。因此,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);