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);
问题是 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);
问题是 foo
的值保持为空字符串。我知道这不是服务器端脚本的问题,因为我要么会收到错误警报,要么至少会收到字符串 "New value:"
。
这是一个演示问题的 JSFiddle:http://jsfiddle.net/wkwjh/
为什么 foo
的值没有改变?
最佳答案
当您提醒 foo
的值时,成功处理程序尚未触发。由于重新分配变量的是成功处理程序,因此它的值仍然是一个空字符串。
事件的时间线看起来像这样:
foo
被赋值为空字符串- 创建并发送 AJAX 请求。
foo
的值被提醒。 (注意foo
还没有改变)- AJAX 请求完成。
foo = "新值:"+ this.responseText;
因为我们想在 foo
改变后提醒它,解决方案是将提醒放在成功回调中。
现在它将在收到 AJAX 响应后执行。
关于javascript - AJAX 不更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883813/