从xhr对象获取请求URL

red*_*are 37 javascript

有没有办法从xhr对象中提取请求URL?我可以通过channel属性看到firebug中的url,但是你无法使用javascript查询它.

小智 31

如果您使用的是jQuery,则可以使用AJAX请求中的"beforeSend"函数来修改jqXHR对象.也就是说,

$.ajax({
...
url: "http://some/url",
beforeSend: function(jqxhr, settings) { jqxhr.requestURL = "http://some/url"; },
...
});
Run Code Online (Sandbox Code Playgroud)

传递给各种回调的jqXHR对象将具有该变量,jqXHR.requestURL您可以访问该变量.

  • 如果你执行`jqxhr.requestURL = settings.url`,你可以在`$ .ajaxSetup`调用中全局设置它. (4认同)

Joe*_*ard 24

通过以下hack,不需要包装器:

var xhrProto = XMLHttpRequest.prototype,
    origOpen = xhrProto.open;

xhrProto.open = function (method, url) {
    this._url = url;
    return origOpen.apply(this, arguments);
};
Run Code Online (Sandbox Code Playgroud)

用法:

var r = new XMLHttpRequest();
r.open('GET', '...', true);
alert(r._url); // opens an alert dialog with '...'
Run Code Online (Sandbox Code Playgroud)


Lio*_*hen 6

我希望我能正确理解你的问题.

使用您自己的对象包装XHR对象应该相当简单,以允许这种功能.

以下是一个过于简化的例子:

// Assumption: GetXHR() returns a new XHR object, cross browser.

function HTTPGet(url, onStartCb, onCompleteCb)
{
  var xhr = GetXHR();
  // Construct your own xhr object that contains the url and the xhr object itself.
  var myXhr = { xhr: xhr, url: url };

  xhr.onreadystatechange = function()
  {
     if (xhr.readyState == 4 && xhr.status == 200)
     {
        onCompleteCb(myXhr);
     }
  };

  xhr.open("GET", url);
  onStartCb(myXhr);
  xhr.send(null);
}
Run Code Online (Sandbox Code Playgroud)

我没有对此进行过广泛的测试,但它应该可以工作并进行一些修改(错误处理,传递参数等),您应该可以将此示例转换为功能完备的解决方案.


Ale*_*lli 5

根据https://developer.mozilla.org/en/XmlHttpRequest,channel如果你拥有提升的权限,你确实可以获得; 但是,它channel是非标准的(可能在其他浏览器中不起作用),实际上http://www.w3.org/TR/XMLHttpRequest/上的W3C规范也没有提及channel"提取请求URL"的任何其他方式.因此,我怀疑在浏览器中没有办法合理地这样做.