Spring MVC + Ajax JSON发布 [英] Spring MVC + Ajax JSON post

查看:73
本文介绍了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.xmlbuild.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发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆