LoginController.java:
@Controller
@RequestMapping("/user")
public class LoginController {
@RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json")
@ResponseBody
public RegInfo receiveData(@RequestBody RegInfo info){//
System.out.println("come here");
System.out.println(info.getRealname());
return info;
}
}
register.xml:
$("#sub").click(function(){
var m = {
"realname": $("#real_name").val(),
"phonenumber": $("#phone_number").val()
};
$.ajax({
type:"POST",
url:"/demo/user/receive",
data:m,
dataType:"json",
contentType:"application/json; charset=utf-8",
async:false,
success:function(data){
alert("nihao");
},
erroe:function(data){
alert("保存失败 ")
}
})
});
RegInfo.java:
public class RegInfo {
private String realname;
private String phonenumber;
//private boolean sex;
public RegInfo(){
}
public void setRealname(String realname){
this.realname= realname;
}
public String getRealname(){
return realname;
}
public void setPhonenumber(String phonenumber){
this.phonenumber = phonenumber;
}
public String getPhonenumber(){
return phonenumber;
}
演示servlet.xml中:
<context:component-scan base-package="com.lhao.core"/>
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven/>
<context:annotation-config/>
我在lib中导入了jackson-annotations-2.1.4.jar,jackson-core-2.1.4.jar,jackson-databind-2.1.4.jar,但是我在控制台中看不到它的打印&#34; 400错误请求&#34;在Chrome中。我尝试了一些方法,但没有效果。
答案 0 :(得分:0)
在将请求发送到服务器之前,您需要将javascript变量转换为json。 JSON.stringify()执行转换。根据上面给出的代码,这应该解决问题。很有希望。
$("#sub").click(function(){
var m = {
"realname": $("#real_name").val(),
"phonenumber": $("#phone_number").val()
};
$.ajax({
type:"POST",
url:"/demo/user/receive",
data:JSON.stringify(m),
dataType:"json",
contentType:"application/json; charset=utf-8",
async:false,
success:function(data){
alert("nihao");
},
erroe:function(data){
alert("保存失败 ")
}
})
});