How can I catch jQuery AJAX errors?

后端 未结 2 1736
你的背包
你的背包 2020-12-31 00:15

When an AJAX request is submitted to a site, server-side errors are easily handled with the jQuery promise approach. .done(), .fail(), etc. However

2条回答
  •  -上瘾入骨i
    2020-12-31 01:00

    try this:

    $.ajax({
        url: remoteURL,
        type: 'GET',
        error: function (err) {
            console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
        }
    }).always(function(jqXHR, textStatus) {
        if (textStatus != "success") {
            alert("Error: " + jqXHR.statusText);
        }
    });
    

    XHR Listener:

    $.ajax({
        url: remoteURL,
        type: 'GET',
        xhr: function(){
            var xhr = new window.XMLHttpRequest();
            xhr.addEventListener("error", function(evt){
                alert("an error occured");
            }, false);
            xhr.addEventListener("abort", function(){
                alert("cancelled");
            }, false);
    
            return xhr;
        },
        error: function (err) {
            console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
        }
    });
    

提交回复
热议问题