我正在尝试通过ajax将数据发送到控制器,但是遇到问题无法加载资源:服务器的响应状态为400(错误请求)。我不知道问题的哪一部分
JS:
var info ={
"questions":{"q1":trim(q1), "q2":trim(q2),"q3":trim(q3),"q4":trim(q4),"q5":trim(q5),"q6":trim(q6),"q7":trim(q7),"q8":trim(q8)},
"answers":{"datetimepicker":datetimepicker,"sexual":sexual,"nation":nation, "province":province,"city":city, "sheng":sheng,"shi":shi,"xian":xian, "height":height,"weight":weight}
};
var info_str = JSON.stringify(info);
$.ajax({
type:'GET',
data:info_str,
contentType: "application/json; charset=utf-8",
dataType: "json",
url :'/yiban',
success :function(data) {
alert(data);
},
error :function(e) {
alert("error");
}
});
Java:
@RequestMapping(value = "/yiban", method = RequestMethod.GET)
public void yiban(HttpServletRequest request)
{
String jsonStr = request.getParameter("info_str");
JSONObject questions = JSONObject.fromObject(jsonStr).getJSONObject("questions");
JSONObject answers = JSONObject.fromObject(jsonStr).getJSONObject("answers");
String q1 = questions.getString("q1");
String ans = answers.getString("nation");
System.out.println(q1);
}
答案 0 :(得分:0)
@RequestMapping(value = "/yiban", method = RequestMethod.POST)
public void yiban(HttpServletRequest request) throws IOException {
//GET method parameter is passed with url , json data can't go with url. json or xml is passed in request boy
// String jsonStr = request.getParameter("info_str");
ServletInputStream inputStream = request.getInputStream();
String jsonStr=StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));
JSONObject questions = JSONObject.fromObject(jsonStr).getJSONObject("questions");
JSONObject answers = JSONObject.fromObject(jsonStr).getJSONObject("answers");
String q1 = questions.getString("q1");
String ans = answers.getString("nation");
System.out.println(q1);
}
上面是我的代码,可在我的项目中使用。
首先,使用POST发送json或xml!
并使用request.getInputStream接收json数据!
其次,您的RequestMappingMethod不返回任何内容,您的前台网站也没有任何内容!
您想返回正面的什么视图?