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

标签 jquery ajax spring spring-mvc http-status-codes

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

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

在我的 Controller 中,提交是通过如下方法处理的:

@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");
}

来自 Controller 的方法的错误响应由此 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;
    }

}

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

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

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

最佳答案

像这样:

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

例如

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

xhr 是 XmlHttpRequest 的缩写。

readyState:值为1:正在加载,2:已加载,3:交互,4:完成

status:HTTP 状态号,如 404 未找到、500 内部服务器错误、200:正常(警告:特殊 IE 问题值:0 已取消)

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

如果即使成功也想检查状态,请使用always:

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

另外,请参阅这篇关于 success-error-complete 与 done-fail-always 的文章
jQuery ajax() using success, error and complete vs .done(), .fail() and always()

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

关于jquery - 使用 jquery 从 ajax 响应获取 Http 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467158/

相关文章:

java - 使用 Jackson JSON Mapper 在 JSON 到 POJO 之间映射时出现 400 错误请求

java - 在 Lucene 文档中添加字段

javascript - HTML 连接 img 标签内的跨度

jquery - Ajax jquery 异步返回值

javascript - 重置单选按钮并使用 jQuery 检查

javascript - Tablesorter AJAX 分页。如何与后端 JSON 正确交互?

javascript - Angularjs 显示 ajax 响应

java - Tapestry 5 和具有相同接口(interface)的 Spring bean

javascript - Jquery:单击复选框时隐藏 slider

javascript - 是否可以在表中找到 td 的数量,然后使用 Javascript 在表标记内应用 col 宽度?