javascript XMLHttpRequest 的替代方案?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9504054/
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
An alternative to XMLHttpRequest?
提问by Jacques Blom
I am writing a Firefox extension. I am using a content script that matches a specific domain. I want to get data from a PHP page. Eventually adding a CSS file to the page to change the styling. The content of the PHP page will be the name of the CSS file I fetch. Here is my content script javascript, the alert returns nothing.
我正在编写一个 Firefox 扩展。我正在使用匹配特定域的内容脚本。我想从 PHP 页面获取数据。最终向页面添加一个 CSS 文件以更改样式。PHP 页面的内容将是我获取的 CSS 文件的名称。这是我的内容脚本 javascript,警报不返回任何内容。
I was told I am limited by the same origin policy. Is there any way I can get data from the php page?
有人告诉我,我受到同源政策的限制。有什么办法可以从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();
回答by Mustafa Dwekat
You can use Fetch API its not supported by Safari or IE for now but its a good alternative.
您可以使用 Safari 或 IE 目前不支持的 Fetch API,但它是一个不错的选择。
You ma use it as:
你可以将它用作:
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?
}
You can get more info from MDN Using Fetch API. You may want More advance usage.
您可以从MDN Using Fetch API获取更多信息。您可能想要更多的高级用法。
Update: you might find this article useful That's so fetch!
更新:你可能会发现这篇文章有用,是如此取!