使用 jquery 从 ajax 响应中获取 Http 状态代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25467158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:06:40  来源:igfitidea点击:

Get Http Status Code from an ajax response with jquery

jqueryajaxspringspring-mvchttp-status-codes

提问by Kleber Mota

In my current spring project, when I submit a form to server, the response is handled by this method:

在我当前的 spring 项目中,当我向服务器提交表单时,响应由以下方法处理:

    $('form.form').each(function () {
        var form = this;
        $(form).ajaxForm(function (data) {
            form.reset();
            $(".alert-info").find("#alert").html(data);
            $(".alert-info").show();
        });
    });

In my controller, the submission is handled by a method like this:

在我的控制器中,提交是由这样的方法处理的:

@RequestMapping(value="cadastra", method=RequestMethod.POST)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public void cadastra(@ModelAttribute("object") E object, BindingResult result, @RequestParam(value="file", required=false) MultipartFile file, @RequestParam(value="icone", required=false) MultipartFile icone, @RequestParam(value="screenshot", required=false) MultipartFile screenshot[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
    serv.cadastra(object);
    serv.upload_picture(object, file, "picture");
    serv.upload_picture(object, icone, "icone");
}

Error responses from the methods from the controller are handled by this ControllerAdvice class:

来自控制器方法的错误响应由这个 ControllerAdvice 类处理:

@ControllerAdvice
@PropertySource({"classpath:error.properties"})
public class GlobalDefaultExceptionHandler {

    @Autowired
    private Environment env;

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        // If the exception is annotated with @ResponseStatus rethrow it and let
        // the framework handle it - like the OrderNotFoundException example
        // at the start of this post.
        // AnnotationUtils is a Spring Framework utility class.
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;
        // Otherwise setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.addObject("msg", e.getLocalizedMessage());
        mav.setViewName("erro");
        return mav;
    }

}

I am looking for a way to read the http status code from response (which can be 1xx, 2xx, 3xx, 4xx or 5xx) in my jquery code, and display a related message according to this code.

我正在寻找一种方法从我的 jquery 代码中的响应(可以是 1xx、2xx、3xx、4xx 或 5xx)中读取 http 状态代码,并根据此代码显示相关消息。

In the network monitor from browser, I can see a successful response already have the code HTTP 201 as implemented in the method; when an error occurs, the response should have a code 4xx or 5xx, depending from exception triggered.

在浏览器的网络监视器中,我可以看到一个成功的响应已经在方法中实现了代码 HTTP 201;发生错误时,响应应具有代码 4xx 或 5xx,具体取决于触发的异常。

In this way, I wonder if anyone can give a hint of how modify my jquery code and my COntrollerAdvice to accomplish this.

这样,我想知道是否有人可以提示如何修改我的 jquery 代码和我的 COntrollerAdvice 来完成此操作。

采纳答案by John S

It looks like you are using the jQuery Form Plugin. If so, the third parameter to the callback function is the xhrobject, and you can get the HTTP status like this:

看起来您正在使用jQuery Form Plugin。如果是这样,回调函数的第三个参数就是xhr对象,您可以像这样获取 HTTP 状态:

$(form).ajaxForm(function (data, statusText, xhr) {
    alert(xhr.status);

jsfiddle

提琴手

回答by Stefan Steiger

Like this:

像这样:

$.ajax({
    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
        //...
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

e.g.

例如

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

xhr is short for XmlHttpRequest.

xhr 是 XmlHttpRequest 的缩写。

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

readyState:值为 1:loading, 2:loaded, 3:interactive, 4:complete

status: the HTTP status number, like 404 not found, 500 internal server error, 200: ok (warning: special IE problem value: 0 cancelled)

status: HTTP 状态号,如 404 not found, 500 internal server error, 200: ok (warning: special IE problem value: 0 cancelled)

responseText: the response from the server - this could be your custom status text (make sure the status code is not 200 OK)

responseText:来自服务器的响应 - 这可能是您的自定义状态文本(确保状态代码不是 200 OK)

If you want to check the status even on success, use always:

如果您想在成功时检查状态,请始终使用:

var jqxhr = $.ajax( "example.php" )
.done(function (data) { alert(data); })
.fail(function (jqXHR, textStatus, errorThrown) { someErrorFunction(); })
.always(function() { alert("complete"); });

Also, see this post on success-error-complete vs. done-fail-always
jQuery ajax() using success, error and complete vs .done(), .fail() and always()

另外,请参阅有关使用成功、错误和完成与 .done()、.fail() 和 always() 的 jQuery ajax() 的关于 success-error-complete vs. done-fail-always
() 的帖子

If you want to setup a global error handling on the page, use ajaxSetup:
http://www.unseenrevolution.com/jquery-ajax-error-handling-function/

如果要在页面上设置全局错误处理,请使用 ajaxSetup:http:
//www.unseenrevolution.com/jquery-ajax-error-handling-function/

回答by aGuegu

To get headers and status in response:

获取响应头和状态:

$.ajax({
    dataType: "json",
    url: url,
    data: data
}).done(function(rs, textStatus, xhr) {
    console.log(xhr.getResponseHeader('X-CUSTOM-HEADER'));
    console.log(xhr.status);
});

see also: Using getResponseHeader with jQuery's ajax method

另请参阅:在 jQuery 的 ajax 方法中使用 getResponseHeader