下面的代码成功地将jsp中的String通过ajax发送到控制器并返回一些String。
如何发回(从控制器到ajax)只包含getter和setter或Boolean的对象?
AJAX:
$.ajax({
type: 'get',
url : 'register/checkUsername',
data : {'typedText' : typedText},
success : function(data) {
$('#doesUsernameAvailable').text("ok " + data);
},
error: function(){
$('#doesUsernameAvailable').text('error');
}
});
控制器:
@RequestMapping(value = "/checkUsername", method = RequestMethod.GET)
public @ResponseBody String checkUsername(String typedText,
HttpServletResponse response){
//some code with return Boolean or Object
return "text from controller";
}
答案 0 :(得分:0)
解决方案:
我没有发布pom.xml。它失踪了:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
现在很少有修改。
AJAX:
$.ajax({
type : 'get',
contentType : "application/json",
url : 'register/checkUsername',
data : {'typedText' : typedText},
dataType : 'json',
success : function(data) {
$('#doesUsernameAvailable').text("ok " + data.isAvailable);
},
error: function(){
$('#doesUsernameAvailable').text('error');
}
});
现在我们可以通过JSON从Controller返回Object。
控制器:
@Controller
@RequestMapping("/register")
public class RegisterController {
@RequestMapping(value = "/checkUsername", method = RequestMethod.GET)
public @ResponseBody CheckUsernameResponse checkUsername(
@RequestParam String typedText){
return new CheckUsernameResponse(true);
}
对象:
public class CheckUsernameResponse {
private Boolean isAvailable;
public CheckUsernameResponse(Boolean isAvailable) {
this.isAvailable = isAvailable;
}
希望有所帮助!