错误jqxhr上的Ajax GET url

Dr *_*izo 15 ajax jquery get jqxhr

我有一个ajax请求,我故意从我的服务器端代码失败来触发错误处理事件.我想知道是否有可能获得它尝试的URL?我想获取该URL并将其注入超链接并重试该请求.

这可能吗?

编辑 我能够看到尝试的URL请求通过FireBug和检查jqxhr对象,console.dir()并且似乎无法找到任何有助于我识别它试图调用的URL的内容.理想情况下,不希望存储全局变量,希望从参数中获取此信息.

在此先感谢,O.

$.ajax({
    type: 'get',
    url: 'somewhere/foo',
    context: this,
    success: this.mySuccess,
    error: this.myError,
    cache: false
});

myError = function (jqXhr, textStatus) {
    alert(jqXhr.url); //Get url of failed request and inject it into hyper link?
};
Run Code Online (Sandbox Code Playgroud)

Kha*_*han 27

保存你url的变量.您可以在错误功能中使用它.显然,url将与ajax请求的url参数中提供的url相同

var url = 'somewhere/foo';

$.ajax({
    type: 'get',
    url: url,
    context: this,
    success: this.mySuccess,
    error: this.myError,
    cache: false,
    error: function(jqXHR, exception) {
       //use url variable here   
    }
});
Run Code Online (Sandbox Code Playgroud)

另一种选择可以是这个

$.ajax({
    type: 'get',
    url: 'https://google.com',
    context: this,
    success: this.mySuccess,
    error: this.myError,
    cache: false,
    beforeSend: function(jqXHR, settings) {
        jqXHR.url = settings.url;
    },
    error: function(jqXHR, exception) {
        alert(jqXHR.url);
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴

  • *显然,该 url 将与 ajax 请求的 url 参数中提供的相同* 不正确,请求可能包含重定向。 (2认同)

nev*_*ves 9

我相信最简单的方法是:

this.url
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案。有数百个 ajax 调用将错误发送到同一个错误处理函数,并且想要进行快速查找和替换,将其作为新的 Ajax-Url 参数添加到错误处理函数中,以便找到罪魁祸首曾是。谢谢你!有用! (2认同)