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

  • Post author:
  • Post category:其他

在我当前的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以完成此操作。