本文介绍了Spring MVC + Ajax JSON发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在将JSON发送到Controller时遇到问题.我不明白我的问题.
I have a problem with send JSON to the Controller. I can't understand my problem.
因此,网址-/notes/{username}/add
Ajax :
$.ajax({ type: "POST", contentType : 'application/json; charset=utf-8', dataType : 'json', url: window.location.pathname, data: JSON.stringify({ title: $("#title").val(), text: $("#text").val() }), success : function() { $("#title").val(""); $("#text").val(""); } });控制器:
@RequestMapping(value = "/{username}/add", method = POST) public void add(@RequestBody Note note) { noteRepository.add(new Note(UserSession.getUser(), note.getTitle(), note.getText())); }注意:
public class Note { private String title; private String text; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } }控制器没有收到来自Ajax的请求.我认为是url问题,但我无法解释为什么以及该怎么做.
Controller don't get request from ajax. I think, problem with url, but I can't why and what to do.
推荐答案将controller修改为:
@RequestMapping(value = "{username}/add", method = RequestMethod.POST) public void add(@RequestBody Note note, @PathVariable("username")String username) { }并且您的ajax调用网址应包含路径变量,如下:
And your ajax call url should include the path variable as:
$.ajax({ type: "POST", contentType : 'application/json; charset=utf-8', dataType : 'json', url : '/Notes/notes/username/add', data: JSON.stringify({ title: $("#title").val(), text: $("#text").val() }), success : function() { $("#title").val(""); $("#text").val(""); } });还要确保您的pom.xml或build.gradle应该具有杰克逊依赖关系,以下是maven项目的示例:
Also make sure your pom.xml or build.gradle should have jackson dependency, below is an example for maven project:
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version> </dependency>更多推荐
Spring MVC + Ajax JSON发布
发布评论