javascript 将 XMLHttpRequest.responseText 存储到变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19213639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing XMLHttpRequest.responseText into variable
提问by Albert
Not very familiar with XMLHttpRequest
s, but am using the cross-origin function in Google Chrome extensions. This works great (I can confirm I get the appropriate data that I need), but I can't seem to store it within the 'response' variable.
对XMLHttpRequest
s不是很熟悉,但正在使用 Google Chrome 扩展中的跨域功能。这很好用(我可以确认我得到了我需要的适当数据),但我似乎无法将它存储在 'response' 变量中。
I'd appreciate any help.
我很感激任何帮助。
function getSource() {
var response;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
response = xmlhttp.responseText;
//IM CORRECTLY SET HERE
}
//I'M ALSO STILL WELL SET HERE
}
//ALL OF A SUDDEN I'M UNDEFINED.
xmlhttp.open("GET","http://www.google.com",true);
xmlhttp.send();
return response;
}
采纳答案by Qantas 94 Heavy
The onreadystatechange
function is asynchronous, that is it will not stop later code from running before the function has completed.
该onreadystatechange
函数是异步的,即它不会在函数完成之前停止后续代码的运行。
For this reason, you're going about this entirely the wrong way. Typically in asynchronous code, callbacks are employed to be able to be called exactly when the onreadystatechange
event fires, so that you know that you are able to retrieve your response text at that time. For example, this would be a case of an asynchronous callback:
出于这个原因,您完全以错误的方式进行了处理。通常在异步代码中,回调用于能够在onreadystatechange
事件触发时准确调用,以便您知道在那个时候可以检索您的响应文本。例如,这将是一个异步回调的情况:
function getSource(callback) {
var response, xmlhttp;
xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200 && callback) callback(xmlhttp.responseText);
}
xmlhttp.open("GET", "http://www.google.com", true);
xmlhttp.send();
}
Think of it like using setTimeout
, which is also asynchronous. The following code will not hang for 100 000 000 000 000 seconds before ending, but rather end immediately, and then wait for the timer to be up to run the function. But by then, the assignment is useless, as it isn't global and nothing else is in the scope of the assignment.
把它想象成 using setTimeout
,它也是异步的。以下代码不会在结束前挂起 100 000 000 000 000 秒,而是立即结束,然后等待计时器启动以运行该函数。但是到那时,分配是无用的,因为它不是全局的,并且没有其他任何东西在分配的范围内。
function test()
{ var a;
setTimeout(function () { a = 1; }, 100000000000000000); //high number for example only
return a; // undefined, the function has completed, but the setTimeout has not run yet
a = 1; // it's like doing this after return, has no effect
}