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

5
在我的当前Spring项目中,当我向服务器提交表单时,响应是由这个方法处理的:
    $('form.form').each(function () {
        var form = this;
        $(form).ajaxForm(function (data) {
            form.reset();
            $(".alert-info").find("#alert").html(data);
            $(".alert-info").show();
        });
    });

在我的控制器中,提交由以下这个方法处理:
@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");
}

此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来实现这一点。

3个回答

6

就像这样:

$.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是XmlHttpRequest的缩写。
readyState:其值为1:正在加载,2:已加载,3:交互式,4:完成。
status:HTTP状态码,比如404未找到、500内部服务器错误、200 OK(警告:特殊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()使用success,error和complete vs.done(),.fail()和always()

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


5

看起来你正在使用jQuery表单插件。如果是的话,回调函数的第三个参数是xhr对象,你可以这样获取HTTP状态:

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

jsfiddle


2

获取响应中的头部和状态:

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

参见:使用jQuery的ajax方法获取getResponseHeader


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接