Jquery spring mvc控制器没有';不能处理纯ajax
我在服务器端有下一个控制器方法:Jquery spring mvc控制器没有';不能处理纯ajax,jquery,json,ajax,spring-mvc,Jquery,Json,Ajax,Spring Mvc,我在服务器端有下一个控制器方法: @RequestMapping(value = {"/templates/test"}, method = RequestMethod.POST, consumes = "application/json") @ResponseBody public String TestURL(@RequestBody List<String> testString, Model model,
@RequestMapping(value = {"/templates/test"}, method =
RequestMethod.POST, consumes = "application/json")
@ResponseBody
public String TestURL(@RequestBody List<String> testString,
Model model,
Locale locale) {
return testString.toString();
}
以及从客户端调用它的两种方法:
1) 通过jQuery:
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'text',
url: "/templates/test",
data: strList,
success: function (result) {
alert(result.responseText);
},
});
-效果很好。控制器处理请求
2) 通过纯AJAX:
var myReq = new XMLHttpRequest();
myReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
myReq.open("POST", "/templates/test", false);
myReq.responseType = 'text';
myReq.send(strList);
-不起作用。控制器不处理请求。根本不调用TestURL方法。您能帮我解决第二个请求,以便能够在控制器上处理它吗?或者建议使用正确的spring版本?我的spring版本是4.3.7
另外,下一个代码运行良好,但它不是我想要的。我需要分析以列出{String}:
控制器:
@RequestMapping(value = {"/templates/test"}, method = RequestMethod.POST) // , consumes = "application/json"
@ResponseBody
public String TestURL(@RequestBody String testString,
Model model,
Locale locale) {
return testString;
}
用户界面:
问题很简单:纯ajax请求是错误的。不允许在打开请求之前调用setRequestHeader。除此之外,如果调用responseType,那么async应该为true
@RequestMapping(value = {"/templates/test"}, method = RequestMethod.POST) // , consumes = "application/json"
@ResponseBody
public String TestURL(@RequestBody String testString,
Model model,
Locale locale) {
return testString;
}
var myReq = new XMLHttpRequest();
//myReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
myReq.open("POST", "/templates/test", false);
myReq.send("aaaa");