我应该从ajax调用的服务器端方法返回什么?
我有以下jQuery脚本:我应该从ajax调用的服务器端方法返回什么?,ajax,jquery,spring-mvc,Ajax,Jquery,Spring Mvc,我有以下jQuery脚本: $(document).ready(function() { $("#resendActivationEmailLink").bind("click", function(event) { $.get($(this).attr("href"), function() { $("#emailNotActivated").html("<span>not yet activated. email sent!<
$(document).ready(function() {
$("#resendActivationEmailLink").bind("click", function(event) {
$.get($(this).attr("href"), function() {
$("#emailNotActivated").html("<span>not yet activated. email sent!</span>");
}, "html");
event.preventDefault();
});
});
一些业务逻辑在服务器上执行,但除了ajax成功或ajax失败之外,在客户端/浏览器端使用的服务器没有真正的结果
现在我真的不确定服务器端方法应该返回什么强>
目前它只返回字符串dummy
,当然这只是暂时的。我应该选择无返回类型(void
)还是null
或其他类型
注意,我可以更改jQuery get方法的数据类型参数
编辑:
我已将服务器端方法更改如下:
@RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET)
public @ResponseBody void resendActivationEmail(@PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
}
@ResponseBody
是必需的,因为这是一个ajax调用。我假设您正在从服务器返回JSON(从您的服务器代码:products=“application/JSON”)
由于您不关心返回的内容,也就是说,您没有在回调函数中处理返回值,$.get之后,您可以只返回“{}”,或者如果您想处理响应,您可以使用以下方法:
{ "success": true }
// or
{ "error": "Error messages here" }
在这种情况下,返回伪值没有意义。如果不使用返回值执行任何操作,则可以执行以下操作:
@RequestMapping(value="/resendActivationEmail/{token}", method=RequestMethod.GET)
@ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
public void resendActivationEmail(@PathVariable String token) {
preferencesService.resendActivationEmail(token);
}
将有一个
204
响应代码而不是200
,但这应该没问题。这真的没关系,不需要任何类型的返回。返回的数据作为参数传递给回调函数。由于回调函数没有任何参数,因此它忽略了这一点。如果函数返回布尔true
或false
,这对于验证是非常有益的。preferencesService函数返回什么?如果它返回布尔值,只需返回该函数返回的任何值即可。然后在jQuery中,您可以告诉用户电子邮件是否真的发送了,或者将它发送到某个日志。@danehillad:preferenceService返回void谢yJay和Barmar!我已经根据你的评论编辑了我的帖子。
@RequestMapping(value="/resendActivationEmail/{token}", method=RequestMethod.GET)
@ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
public void resendActivationEmail(@PathVariable String token) {
preferencesService.resendActivationEmail(token);
}