Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jquery从ajax响应获取Http状态代码_Jquery_Ajax_Spring_Spring Mvc_Http Status Codes - Fatal编程技术网

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

使用jquery从ajax响应获取Http状态代码,jquery,ajax,spring,spring-mvc,http-status-codes,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-in

在我当前的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");
}
$(form).ajaxForm(function (data, statusText, xhr) {
    alert(xhr.status);
来自控制器的方法的错误响应由此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代码中的响应(可以是1xx、2xx、3xx、4xx或5xx)读取http状态代码,并根据此代码显示相关消息

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

通过这种方式,我想知道是否有人可以提示如何修改我的jquery代码和COntrollerAdvice来实现这一点。

如下:

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

xhr是XmlHttpRequest的缩写

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

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

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

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

var jqxhr = $.ajax( "example.php" )
.done(function (data) { alert(data); })
.fail(function (jqXHR, textStatus, errorThrown) { someErrorFunction(); })
.always(function() { alert("complete"); });
另外,请参阅这篇关于成功-错误-完成与失败-总是失败的帖子

如果要在页面上设置全局错误处理,请使用ajaxSetup:

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

@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");
}
$(form).ajaxForm(function (data, statusText, xhr) {
    alert(xhr.status);

要获取响应中的标题和状态:

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