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

Ajax call always return error in springMVC

本文关键字:返回 错误 调用 springMVC Ajax      更新时间:2023-09-26

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',并从控制器我返回一个布尔值为真,但每次错误方法在jsp中执行而不是成功方法。那么我如何通过从控制器传递真值来调用成功方法呢?

请试试这个:

@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);
});

尽管您做出了断言,但您没有返回布尔值。你在模型中放置了一些名为'success'和'error'的字符串属性,并转发给名为"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响应体(而不是放置在模型中,或解释为视图名)