替代XMLHttpRequest的方案?

6
我正在编写Firefox扩展程序。我使用了一个匹配特定域名的内容脚本。我想从PHP页面获取数据,最终将CSS文件添加到页面以改变样式。PHP页面的内容将是我提取的CSS文件的名称。这是我的内容脚本javascript,警报没有返回任何内容。
我被告知同源策略限制了我的操作。有没有办法可以从php页面获取数据?
function getData() {
            client = new XMLHttpRequest();
            try{
                client.open('GET','http://localhost:8888/istyla/login/popuplogin/myaccount.php');                   
            } catch (e){
                alert( "error while opening " + e.message );
            }

            client.onreadystatechange = function(){
                if (client.readyState ==4){
                        user_data = client.responseText;
                        var currenttheme = user_data;
                        alert (currenttheme);
                }
            }

            client.send(null);
}

getData();

重要的上下文缺失:这是使用Add-on SDK构建的扩展程序的内容脚本。我已经在这里回答了你的问题(http://stackoverflow.com/a/9506835/785541),不会再次回答。 - Wladimir Palant
参见:https://jakearchibald.com/2015/thats-so-fetch/ - dreftymac
2个回答

7

您可以使用Fetch API,目前Safari和IE不支持它,但这是一个很好的替代方案。

您可以这样使用:

function getData(){
    fetch('flowers.jpg').then(function(response) {
         return response.blob();
    })
}


if(self.fetch) {
    // run my fetch request here
    var resp = getData();
} else {
    // do something with XMLHttpRequest?
}

你可以从MDN 使用 Fetch API获取更多信息。您可能想要更高级的用法

更新:你可能会发现这篇文章有用那么酷炫!


7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接