[英]Ajax call always return error in springMVC
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中執行錯誤方法而不是成功方法,那么我該如何調用成功方法通過傳遞上述控制器的真實值。任何幫助將不勝感激。
盡管有斷言,但您沒有返回布爾值。 您將一些名為'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響應主體(而不是放置在Model中或解釋為視圖名稱)。
請嘗試以下方法:
@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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.