在编写Ajax通用错误处理程序时,经常需要记录发生错误的XMLHttpRequest的请求URL。但查询文档,并未找到从XMLHttpRequest中获取请求URL的方法。
在javascript - Get request url from xhr object - Stack Overflow中提供了一种可能的实现方式:为浏览器原生的XMLHttpRequest包上一层。实现代码如下:
var xhrProto = XMLHttpRequest.prototype,
origOpen = xhrProto.open;
xhrProto.open = function (method, url) {
this._url = url;
return origOpen.apply(this, arguments);
};
使用示例:
var r = new XMLHttpRequest();
r.open('GET', '...', true);
alert(r._url); // opens an alert dialog with '...'