如何从控制器调用ajax成功和错误功能?

时间:2014-05-24 05:24:11

标签: ajax spring-mvc

我有ajax功能

$.ajax({
    ....
    type: "POST",  
    url: "",
    data: "", 
    success: function(){  
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
    }       
});

&安培;控制器代码是

public @ResponseBody
GenericResponse abc() {
    try {
        ....
    } catch (Exception ex) {
        ex.printStackTrace();
        return new GenericResponse("Failed", ex.getMessage(), 500);
    }
    return new GenericResponse("Success", "", 200);
}

GenericResponse是

public class GenericResponse 
{

    private String status;

    private String error;

    private int code;

    public GenericResponse(String s, String e, int c)
    {
        this.status = s;
        this.error = e;
        this.code = c;
    }
....
}

所以成功与否失败我发送带有状态的genericresponse,但两者都进入成功回调函数。 我知道它是gennericResponse所以ajax会认为它只是成功。如果有异常 我希望它转到错误回调函数。怎么做?

1 个答案:

答案 0 :(得分:2)

不要返回GenericResponse,而是尝试返回ResponseEntity。

你会这样做:

return new ResponseEntity<GenericResponse>(successGenericResponse, HttpStatus.OK);

return new ResponseEntity<GenericResponse>(failGenericResponse, HttpStatus.INTERNAL_SERVER_ERROR);