【问题标题】:Spring MVC + Ajax error 400Spring MVC + Ajax 错误 400
【发布时间】:2017-04-09 03:12:05
【问题描述】:

我在 Spring MVC 上有一个简单的 java 应用程序,我向 Spring 控制器发送 ajax 请求。当我在 AJAX 调用中设置标题 "Accept"、"application/json" 和 "Content-Type"、"application/json;charset=utf-8" 时,我得到错误 400 在调试器中,当我删除它时,我得到 错误 415。

如果我将控制器方法签名更改为 public String logoutPage (@RequestBody String obyavleniye),我会得到 JSON 字符串。在控制器中解析请求会出现什么问题?

JS方法:

$("#advertForm").submit(function(e) {
        e.preventDefault();
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        var obyavleniye = {
            title: "Title",
            price: "80",
            description: "desc",
            date: "2016-11-07 18:30:21",
            authorid: "2",
            category: "A",
            state: "new",
            img1: "http",
            img2: "http",
            img3: "http",
            img4: "http",
        };
        var post_data = JSON.stringify(obyavleniye);

        console.log(post_data);
        $.ajax({
            url : "/upload",
            type: "POST",
            dataType: 'json',
            data: post_data,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
                xhr.setRequestHeader(header, token);
            },
            complete: function() {
                console.log("Sent");
            },
            success: function (response) {
                console.log("success");
                console.log("response" + response);
            },
            error: function (data) {
                console.log("error");
                console.log(data);
            }
        });
    });

控制器方法:

@ResponseBody
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public String logoutPage (@RequestBody Advert obyavleniye) {
//    public String logoutPage (@RequestBody String obyavleniye) {
        System.out.println("Enter: " + obyavleniye);
        this.advertService.addAdvert(obyavleniye);
//        return "{\"msg\":\"success\"}";
        return "{\"title\":\"Title\",\"price\":\"80\",\"description\":\"normm\",\"date\":\"2016-11-07 18:30:21\",\"authorid\":\"2\",\"category\":\"A\",\"state\":\"new\",\"img1\":\"http\",\"img2\":\"http\",\"img3\":\"http\",\"img4\":\"http\"}";
    }

【问题讨论】:

  • 请指定广告类属性。

标签: json ajax spring


【解决方案1】:

我的示例代码。

js

  Company.prototype.saveCompanyLocation = function() {
        /* company */
        var companyIdx = $('#companyIdx').val();
        var locationIdx = $('#locationIdx').val();

        var data = {
            idx : locationIdx,

            postCode : $('#postCode').val(),
            address : $('#address').val(),
            detailAddress : $('#detailAddress').val(),

            tel : $('#tel').val(),
            fax : $('#fax').val(),
            email : $('#email').val(),
            language : $("#language").val(),

            latitude : $('#latitude').val(),
            longtitude : $('#longtitude').val()

        };

        data = JSON.stringify(data);

        $.ajax({
            url : "/gpim/company/settings/location/save/" + companyIdx,
            type : 'POST',
            data : data,
            contentType : 'application/json',

            success : function(response) {
                if (response == "success") {
                    document.location.reload(true);
                } else {
                    $("#editMsg").text("you can`t save location information.");
                }
            },
            error : function(request, status, error) {

            }
        });
    };

控制器

@RequestMapping(value = "/settings/location/save/{companyIdx}", method = RequestMethod.POST)
    public @ResponseBody String saveLocation(@PathVariable int companyIdx, @RequestBody CompanyLocation location) {
        Company company = companyService.findCompanyByIdx(companyIdx);

        company = companyService.saveCompanyLocation(company, location);

        if (company != null) {
            return "success";
        }

        return "fail";
    }

【讨论】:

  • 而区别在哪里?我不明白为什么会出错。
  • 您在“Accept”、“application/json”中使用 HTTP 标头。然后您的控制器采用(produce =“application/json”)或使用“contentType”、“application/json”。然后你的控制器采取(消耗=“应用程序/json”)。但你使用两种情况。
  • 你在 js 中使用 dataType : 'json'。它是您的控制器返回 responseType。您使用 dataType : 'text' 和 var data = eval( '(' + response + ')' );或者如果使用'json'。您可以搜索 dataType : 'json' 和服务器代码。很长的评论。
  • 谢谢!我更改了 dataType: 'text' 并且它有效。也许我改变了其他东西,但我认为这是主要问题。
【解决方案2】:

执行以下步骤:

1) 尝试将 jackson jar 文件保留在您的类路径中

2) 八次您在发送 ajax 请求时删除了数据类型,即,

dataType : "json"

或者您必须生成如下应用程序/json 响应

@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

3) 检查您的 DTO 或 Advert 类属性,哪种类型应与传入请求匹配。即请求参数应与 DTO 成员的名称和类型匹配。

这些是避免您的情况的可能方法。

【讨论】:

    猜你喜欢
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多