无法在“Firefox”扩展中发送跨域请求

Rah*_*rma 3 javascript ajax firefox jquery firefox-addon

我正在尝试cross-domain通过使用jsonpXMLHttpRequest使用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();
Run Code Online (Sandbox Code Playgroud)

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);
     }
});
Run Code Online (Sandbox Code Playgroud)

两种方法具有相同的行为。每当我发送请求时,它只是继续加载(即使我不确定它是否发送请求)并且什么都不做。

还有我的 php 代码:

PHP代码:

header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';
Run Code Online (Sandbox Code Playgroud)

whi*_*101 5

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": [
    {
      // ...
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)