Asa*_*din 4 javascript ajax jquery asynchronous
我正在发出一个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不变?
我正在发出一个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不变?
在您提醒值时foo,成功处理程序尚未触发.由于成功处理程序重新分配变量,因此其值仍为空字符串.
事件的时间表看起来像这样:
foo 被赋予空字符串foo提醒的价值.(注意foo还没改变)foo = "New value:" + this.responseText;由于我们想要foo 在更改后提醒值,解决方案是将警报置于成功回调中.
现在它将在收到AJAX响应后执行.
| 归档时间: |
|
| 查看次数: |
4359 次 |
| 最近记录: |