Ajax调用总是在springMVC中返回错误

时间:2015-08-28 14:51:33

标签: javascript jquery ajax spring-mvc

Ajax电话:

$.ajax({
    type:'post',
        url:'https://hybris.local:9002/store/verify?productCodePost='+productid,
        data : {notifyemail : notifyemail},
        dataType : "text",
        success : successmethod,

        error : function(data, status) {
            //alert("Error  "+status);

            $('#showbecomepartnerMessage').show();

         }
 });

alert("test values are"+notifyemail); 

document.getElementById('notifyemail').value='';

}

function successmethod(data) {

    if (data != null) {
        alert('Success');
        $('#showemailMessage').show();
    } else {
        alert('Error');
    }

}

控制器:

@RequestMapping(value = "/verify", method = RequestMethod.POST, produces = "application/json")
    public String verifyEmail(@RequestParam("productCodePost") final String code, final Model model,
            @Valid final AddToCartForm form)
    {


        System.out.println("Inside Verify method");
        final String email = form.getNotifyemail();
        System.out.println("Email is " + email);
        System.out.println("Product code is== " + code);
        final Boolean status = true;

        if (email != null)
        {

            System.out.println("Email id is" + email);

            notifyStockEmail(email, code);


        }


        if (status.booleanValue())
        {
            System.out.println("value of Boolean " + status.booleanValue());
            //return "success";
            model.addAttribute("success", "success");
        }
        else
        {

            //return "fail";
            model.addAttribute("error", "error");
        }
        return "success";
    }

在上面的代码中,我正在进行ajax调用并调用控制器'/ verify',并且从控制器返回一个布尔值为true但每次都在jsp中执行错误方法而不是成功方法。所以我怎么能如上所述,通过从控制器传递true值来调用成功方法。非常感谢。

2 个答案:

答案 0 :(得分:0)

尽管你有断言,但你没有返回一个布尔值。您在模型中放置了一些名为“success”和“error”的String属性,并转发到名为“success”的视图,该视图可能存在或不存在。

如果您只是想将布尔值true | false写入响应流,那么您可以执行以下操作。

添加@ResponseBody注释:

@RequestMapping(value = "/verify", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody boolean verifyEmail(@RequestParam("productCodePost") final String code, final Model model,
            @Valid final AddToCartForm form){

   boolean status = false;

   //check and set status.

   return status;
}

请参阅:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

  

这个注释可以放在一个方法上并指示返回   type应直接写入HTTP响应主体(而不是   放在模型中,或解释为视图名称)

答案 1 :(得分:0)

请试试这个:

@RequestMapping(value = "/verify", method = RequestMethod.POST)
public @ResponseBody String verifyEmail(@RequestParam("productCodePost") final String code) {

    //do what you want and return your status
    return "OK";
}

你的ajax电话应该​​是这样的:

$.ajax({
    type:'post',
        url:'https://hybris.local:9002/store/verify?productCodePost='+productid
 }).success(function(data) {
  successmethod(data);
});