Show proper error messages with jQuery AJAX

后端 未结 2 771
南旧
南旧 2021-02-06 05:03

Currently if I have an error with an ajax request such as submitting a form (I\'m using ASP.NET MVC 3) it will show something like \'Internal Server Error\'.

But if I do

相关标签:
2条回答
  • 2021-02-06 05:16

    Although I wouldnt recommend showing the user an error number with the actual response error message this is how you can do this by adding the error callback

    error: function(xhr,err){
        alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
        alert("responseText: "+xhr.responseText);
    }
    

    xhr is XmlHttpRequest.

    readyState values are 1:loading, 2:loaded, 3:interactive, 4:complete.

    status is the HTTP status number, i.e. 404: not found, 500: server error, 200: ok.

    responseText is the response from the server - this could be text or JSON from the web service, or HTML from the web server.

    0 讨论(0)
  • 2021-02-06 05:36

    This code will replace the current page's contents with the error that came back from the ajax request.

    jQuery(document).ajaxError(function (event, request, settings) {
        if (request.status === 500) {
            $(document.body).html(request.responseText);
        } else if (request.status === 401) {
            // redirect to login, 401 means session is expired.
            window.location.href = "login page url";
        }
    });
    
    0 讨论(0)
提交回复
热议问题