Alb*_*ert 5 javascript ajax google-chrome-extension
对XMLHttpRequests不是很熟悉,但正在使用 Google Chrome 扩展中的跨域功能。这很好用(我可以确认我得到了我需要的适当数据),但我似乎无法将它存储在 'response' 变量中。
我很感激任何帮助。
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;
}
Run Code Online (Sandbox Code Playgroud)
该onreadystatechange函数是异步的,即它不会在函数完成之前停止后续代码的运行。
出于这个原因,您完全以错误的方式进行了处理。通常在异步代码中,回调用于能够在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();
}
Run Code Online (Sandbox Code Playgroud)
把它想象成 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15654 次 |
| 最近记录: |