【发布时间】:2017-04-14 14:50:01
【问题描述】:
我一直在努力将 Jquery ajax 以 @RequestBody 的形式发布到 Spring 控制器中。
我能够发送 JSON 字符串并在控制器中捕获 JSON 字符串。但是,无法将 JSON 字符串从 jquery ajax 发送到控制器 [无法转换为对象]。
下面是代码sn-p:
**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);
}
});
}
// 响应对象初始化:
<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:localhost:8080/testSpringmvc-1.0/ajaxhai.do Request Method:POST Status Code:400 Bad Request Remote Address:[::1]:8080*/
-
你说得对,我对 dataType 和 contentType 感到困惑。
标签: jquery ajax spring-mvc