0
我一直在为jQuery的ajax后数据挣扎到Spring控制器作为@RequestBody。Spring控制器和JQuery的Ajax无法将Json字符串转换为对象
我能够发送JSON字符串并捕获控制器中的JSON字符串。但是,无法将JSON字符串从jquery ajax发送到控制器[无法转换为对象]。
下面的代码片段:
**Ajax Call:**
function postLoad(){
$.ajax({
type : 'POST',
url : "ajaxhai.do",
contentType : "application/json",
cache : false,
data : responseObject, **//json-String**
dataType :"html",
success : function(data, textStatus) {
console.log("POST success");
$("#ajaxContent").html(data);
},
error : function(request, status, error) {
console.log("failed" + error);
}
});
}
//初始化responseObject:
<c:if test='${not empty ajitems}'>
var responseObject = JSON.stringify('${ajitems}');
</c:if>
// ${ajitems}--> is the model attribute and setting it in javascript to //send it back to controller through ajax call
//Controller:
@RequestMapping(value = "ajaxhai.do", method = RequestMethod.POST,consumes="application/json") **//unable to convert to requestBody**
public String testAjaxPost(@RequestBody AjaxDto[] ajaxRes, Model model,
HttpServletRequest request, HttpServletResponse response) {
System.out.println(ajaxRes);
return "ajaxform";
}
我有杰克逊的依赖以及在POM:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.3</version>
</dependency>
它总是说:
jquery-3.2.1.min.js:4 POST http://localhost:8080/testSpringmvc-1.0/ajaxhai.do 400 (Bad Request)
但是当我通过以下方式改变控制器,它正在般的魅力:
@RequestMapping(value = "ajaxhai.do", method = RequestMethod.POST,consumes="application/json")**//Please note : here it is String and not Object[]**
public String testAjaxPost(@RequestBody String ajaxRes, Model model,
HttpServletRequest request, HttpServletResponse response) {
System.out.println(ajaxRes);
Gson gson = new Gson();
TestAjaxDto[] mcArray = gson.fromJson(ajaxRes, TestAjaxDto[].class);
List<TestAjaxDto> mcList = new ArrayList<TestAjaxDto>(Arrays.asList(mcArray));
System.out.println(mcList);
return "ajaxform";
}
那是什么,我在这里失踪?我试过所有的自动JSON转换的可能性仍然没有运气。
任何帮助表示赞赏。
谢谢。
您在ajax请求中提到dataType为html。我认为它应该是'application/json'或者只是删除它。 –
@VijendraKulhade dataType意味着预期的正确的返回类型。即使我试了一下,但仍收到的响应是相同的/*RequestURL:http://localhost:8080/testSpringmvc-1.0/ajaxhai.do 请求方法:POST 状态代码:400错误的请求 远程地址:[: :1]:8080 */ – venkatVJ
你说得对我感到困惑dataType和contentType。 –