How do I get the HTTP status code with jQuery?

前端 未结 9 1691
逝去的感伤
逝去的感伤 2020-11-27 13:34

I want to check if a page returns the status code 401. Is this possible?

Here is my try, but it only returns 0.

$.ajax({
    url: \"http://my-ip/tes         


        
9条回答
  •  广开言路
    2020-11-27 14:23

    I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.

    The best way to combat this is to call the .always chain method and do a bit of cleaning up. Here is my code.

    $.ajax({
            ...
        }).always(function(data, textStatus, xhr) {
            var responseCode = null;
            if (textStatus === "error") {
                // data variable is actually xhr
                responseCode = data.status;
                if (data.responseText) {
                    try {
                        data = JSON.parse(data.responseText);
                    } catch (e) {
                        // Ignore
                    }
                }
            } else {
                responseCode = xhr.status;
            }
    
            console.log("Response code", responseCode);
            console.log("JSON Data", data);
        });
    

提交回复
热议问题