AJAX没有更新变量

Asa*_*din 4 javascript ajax jquery asynchronous

jQuery的

我正在发出一个AJAX请求,foo用服务器的响应更新变量()的值.这是我正在使用的代码:

//## My variable ##

var foo = "";


//## Send request ##

$.ajax({
    url: "/",
    dataType: "text",
    success: function(response) {
        foo = "New value:" + response;
    },
    error: function() {
        alert('There was a problem with the request.');
    }
});


//## Alert updated variable ##

alert(foo);
Run Code Online (Sandbox Code Playgroud)

问题是值foo仍为空字符串.我知道这不是服务器端脚本的问题,因为我要么得到错误警报,要么至少得到字符串"New value:".

这是一个演示问题的JSFiddle:http://jsfiddle.net/GGDX7/

为什么价值foo不变?


纯JS

我正在发出一个AJAX请求,foo用服务器的响应更新变量()的值.这是我正在使用的代码:

//## Compatibility ##

var myRequest;
if (window.XMLHttpRequest) {
    myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}


//## My variable ##

var foo = "";


//## Response handler ##

myRequest.onreadystatechange = function() {
    if (this.readyState === 4) {
        if (this.status === 200) {
            foo = "New value:" + this.responseText;
        } else {
            alert('There was a problem with the request.');
        }
    }
};


//## Send request ##

myRequest.open('GET', "response.php");
myRequest.send();


//## Alert updated variable ##

alert(foo);
Run Code Online (Sandbox Code Playgroud)

问题是foo保持空字符串的值.我知道这不是服务器端脚本的问题,因为我要么得到错误警报,要么至少得到字符串"New value:".

这是一个演示问题的JSFiddle:http://jsfiddle.net/wkwjh/

为什么价值foo不变?

Den*_*ret 5

在您提醒值时foo,成功处理程序尚未触发.由于成功处理程序重新分配变量,因此其值仍为空字符串.

事件的时间表看起来像这样:

  1. foo 被赋予空字符串
  2. 创建和分派AJAX请求.
  3. foo提醒的价值.(注意foo还没改变)
  4. AJAX请求完成.
  5. foo = "New value:" + this.responseText;

由于我们想要foo 更改提醒值,解决方案是将警报置于成功回调中.

现在它将在收到AJAX响应后执行.