我在服务器端有下一个 Controller 方法:
@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();
}
UI(java 脚本)的先决条件:
var statList = [];
statList.push('aaa');
statList.push('bbb');
var strList = JSON.stringify(statList);
以及从客户端调用它的两种方法:
1) 通过 jQuery:
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'text',
url: "/templates/test",
data: strList,
success: function (result) {
alert(result.responseText);
},
});
- 效果很好。 Controller 处理请求。
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);
- 不起作用。 Controller 不处理请求。根本没有调用方法 TestURL。您能帮我修复第二个请求以便能够在 Controller 上处理它吗?或者建议合适的 Spring 版本?我的 Spring 版本是 4.3.7。
附注下一个代码运行良好,但这不是我想要的。我需要解析到 List{String}:
Controller :
@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");
最佳答案
问题很简单:纯ajax请求是错误的。在打开请求之前不允许调用setRequestHeader。除此之外,如果调用responseType那么async应该为true
关于jquery - spring mvc Controller 不处理纯ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46000098/