Spring MVC + Ajax JSON发布

编程入门 行业动态 更新时间:2024-10-25 04:18:28
本文介绍了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发布

本文发布于:2023-11-24 21:18:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626869.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MVC   Spring   JSON   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!