无法在`Firefox`扩展名中发送跨域请求

时间:2017-03-14 04:47:47

标签: javascript jquery ajax firefox firefox-addon

我正在尝试使用cross-domainjsonp 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).')';

2 个答案:

答案 0 :(得分:4)

XMLHttpRequest可以正常工作,不需要jsonp。在manifest.json中,请确保您要为您要发布的域申请权限 - Chrome不需要XHR的权限,但Firefox可以。此错误在Firefox中显示为XHR中的http代码404,但在网络面板中没有活动。如果您获得http代码0,那么您也会遇到CORS或混合内容安全问题。

{
  "manifest_version": 2,
  "name": "web extension",
  "version": "1",
  "permissions": [
    "http://example.com/"
  ],
  "content_scripts": [
    {
      // ...
    }
  ]
}

答案 1 :(得分:0)

尝试在xhr请求中使用new XDomainRequest()。 XDomainRequest是HTTP访问控制(CORS)的实现。

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();