Javascript 无法在“Firefox”扩展中发送跨域请求
我正在尝试使用Javascript 无法在“Firefox”扩展中发送跨域请求,javascript,jquery,ajax,firefox,firefox-addon,Javascript,Jquery,Ajax,Firefox,Firefox Addon,我正在尝试使用jsonp或XMLHttpRequest和GET方法访问跨域数据。我的代码: XMLHttpRequest var xhr = new XMLHttpRequest(); xhr.open("GET", "http://example.com/ajax.php?code=BSE", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { alert(xhr.respons
jsonp
或XMLHttpRequest
和GET
方法访问跨域
数据。我的代码:
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/ajax.php?code=BSE", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
xhr.send();
JsonP
$.ajax({
type: 'GET',
url: "http://example.com/ajax.php?code=BSE",
dataType: "jsonp",
jsonpCallback: "jsonp_callback",
crossDomain: true,
success: function(res){
console.log(res);
}
});
两种方法具有相同的行为。每当我发送请求时,只需继续加载(即使我不确定它是否发送请求),什么也不做
和我的php代码:
PHP代码:
header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';
XMLHttpRequest
可以正常工作,不需要jsonp。在你的manifest.json
中,确保你为你发布到的域请求权限——Chrome不需要XHR权限,但Firefox需要。此错误在Firefox中以http代码404在XHR中显示,但在网络面板中没有任何活动。如果您得到http代码0,则还存在CORS或混合内容安全问题
{
"manifest_version": 2,
"name": "web extension",
"version": "1",
"permissions": [
"http://example.com/"
],
"content_scripts": [
{
// ...
}
]
}
尝试在xhr请求中使用
新XDomainRequest()
。XDomainRequest是HTTP访问控制(CORS)的一个实现
对所有其他jquery函数都工作正常..同样的
XMLHttpRequest
在chrome扩展中工作完美..jsonpCallback:“jsonp_callback”,
这个回调函数真的存在吗?我希望代表您进行的编辑修复了您的打字错误,因为现在,XHR代码是valid@Alive死亡:我对jsonp不太了解,真的上帝啊,你救了我的命,这是一个秘密的选择。。。主题施法者可以根据需要标记此答案!谢谢,chrome中不需要它,但Firefox中需要它
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'http://example.com/ajax.php?code=BSE';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send();