【问题标题】:Unable to send cross-domain request in `Firefox` extension无法在“Firefox”扩展中发送跨域请求
【发布时间】:2017-03-14 04:47:46
【问题描述】:

我正在尝试使用jsonpXMLHttpRequestGET 方法访问cross-domain 数据。我的代码:

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).')';

【问题讨论】:

  • 是的..所有其他jquery函数都工作正常..
  • 同样的 XMLHttpRequest 在 chrome 扩展中完美运行..
  • jsonpCallback: "jsonp_callback",这个回调函数真的存在吗
  • 我希望以您的名义进行的编辑修正了您的错字,因为现在 XHR 代码有效
  • @Alive to Die:我对jsonp真的了解不多

标签: javascript jquery ajax firefox firefox-addon


【解决方案1】:

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": [
    {
      // ...
    }
  ]
}

【讨论】:

  • 天哪,你救了我的命,这是一个如此隐秘的选择……主题施法者可以根据需要标记这个答案!
  • 谢谢,在 chrome 中不需要它,但在 Firefox 中是这样的
【解决方案2】:

尝试在您的 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();

【讨论】:

    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 2016-12-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多