AJAX没有更新变量
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 = "New value:" + this.responseText;
由于我们想要在更改之后提醒foo
的值,解决方案是将警报放入成功回调中。
现在它将在收到AJAX响应后执行。
“AJAX”中的(第一个) A表示异步 。 事务不会立即发生,因此您的alert()
会在远程调用完成之前发生一段时间。
问题是您的警报在请求完成之前被触发。 试试这段代码:
我已将警报放入$.ajax
的回调函数中,这意味着只有在.ajax
部分完成后才会触发回调函数。 这将传输新数据,设置变量,然后提醒它,而不是同时调用请求和警告变量。
$.ajax({ url: "/", dataType: "text", success: function(response) { foo = "New value:" + response; alert(foo); }, error: function() { alert('There was a problem with the request.'); } });
问题很简单……
alert(foo);
将在处理请求时执行, foo
将不会被更改。
如果你这样做:
$.ajax({ url: "/", dataType: "text", success: function(response) { foo = "New value:" + response; alert(foo); }, error: function() { alert('There was a problem with the request.'); } });
你会发现它按预期工作
在Ajax请求完成之前,您的警报正在执行。 请尝试以下方法。 var foo =“”;
$.ajax({ url: "/", dataType: "text", success: function(response) { foo = "New value:" + response; alert(foo); }, error: function() { alert('There was a problem with the request.'); } });