Google chrome extension XMLHttpRequest在google chrome扩展中不起作用

Google chrome extension XMLHttpRequest在google chrome扩展中不起作用,google-chrome-extension,xmlhttprequest,Google Chrome Extension,Xmlhttprequest,我已经为此绞尽脑汁很长时间了。我正试图向谷歌发送一个xmlhttprequest,并将相应的数据记录到我的控制台中。 我的代码: 我在manifest.json中添加了权限。但是,当我调试时,它不会打印任何内容。只是一条空线。我在这里做错了什么。您的错误实际上是将异步XMLHttpRequest函数视为同步。当您调用console.log时,Google没有响应。您的代码应该如下所示: sendRequest(); function sendRequest() { var req =

我已经为此绞尽脑汁很长时间了。我正试图向谷歌发送一个xmlhttprequest,并将相应的数据记录到我的控制台中。 我的代码:


我在manifest.json中添加了权限。但是,当我调试时,它不会打印任何内容。只是一条空线。我在这里做错了什么。

您的错误实际上是将异步XMLHttpRequest函数视为同步。当您调用console.log时,Google没有响应。您的代码应该如下所示:

sendRequest();

function sendRequest() {
    var req = new XMLHttpRequest();
    req.open("GET", "http://www.google.com", true);
    req.addEventListener("load", function(e) {
        console.log(req.responseText);
    }, false)

    req.send(null);
}

您的错误实际上是将异步XMLHttpRequest函数视为同步。当您调用console.log时,Google没有响应。您的代码应该如下所示:

sendRequest();

function sendRequest() {
    var req = new XMLHttpRequest();
    req.open("GET", "http://www.google.com", true);
    req.addEventListener("load", function(e) {
        console.log(req.responseText);
    }, false)

    req.send(null);
}

德米特里·索林的答案很好。这里有一个更通用的版本:

sendRequest('http://www.google.com/,函数(响应){
警报(“我的请求返回此:”+响应);
}); 
函数sendRequest(url、回调){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
回调(xhr.responseText);
}
};
xhr.open(“GET”,url,true);
xhr.send();
}

德米特里·索林的答案很好。这里有一个更通用的版本:

sendRequest('http://www.google.com/,函数(响应){
警报(“我的请求返回此:”+响应);
}); 
函数sendRequest(url、回调){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
回调(xhr.responseText);
}
};
xhr.open(“GET”,url,true);
xhr.send();
}

因为您正在尝试执行跨域请求。控制台中显示:“XMLHttpRequest无法加载。请求的资源上不存在“Access Control Allow Origin”头。因此不允许访问源“”。是否可以将此头包含在html文件本身中?否。它是HTTP协议的一部分。它与HTML文档无关。请参阅此页了解更多详细信息:因为您正在尝试执行跨域请求。控制台中显示:“XMLHttpRequest无法加载。请求的资源上不存在“Access Control Allow Origin”头。因此不允许访问源“”。是否可以将此头包含在html文件本身中?否。它是HTTP协议的一部分。它与HTML文档无关。有关更多详细信息,请参阅本页:
sendRequest();

function sendRequest() {
    var req = new XMLHttpRequest();
    req.open("GET", "http://www.google.com", false );// set the third argument to false
    req.send(null);
    console.log(req.responseText);
}