JavaScript: Ajax请求后的全局变量[重复]

时间:2022-06-03 20:22:10

This question already has an answer here:

这个问题已经有了答案:

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的值?

4 个解决方案

#1


72  

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 default which 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.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.

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


The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function 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
// ...

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

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

Douglas Crockford (YUI Blog)

道格拉斯Crockford(YUI的博客)

#2


6  

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 $.post out into the longer $.ajax call and adds the async option).

AJAX代表异步JavaScript和XML。因此,发送到服务器的post与函数的其余部分不同步。尝试一些类似这样的代码(它只破坏了简写$。发布到更长的$。ajax调用并添加异步选项)。

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!

希望这可以帮助!

#3


4  

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函数接受一个回调参数,告诉您何时完成post。您不能像这样在全局范围内发出警报,并期望这个帖子已经完成。你必须把它移到回调函数。

#4


3  

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after 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);

#1


72  

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 default which 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.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.

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


The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function 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
// ...

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

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

Douglas Crockford (YUI Blog)

道格拉斯Crockford(YUI的博客)

#2


6  

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 $.post out into the longer $.ajax call and adds the async option).

AJAX代表异步JavaScript和XML。因此,发送到服务器的post与函数的其余部分不同步。尝试一些类似这样的代码(它只破坏了简写$。发布到更长的$。ajax调用并添加异步选项)。

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!

希望这可以帮助!

#3


4  

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函数接受一个回调参数,告诉您何时完成post。您不能像这样在全局范围内发出警报,并期望这个帖子已经完成。你必须把它移到回调函数。

#4


3  

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after 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);