【问题标题】:send json via native ajax通过本机 ajax 发送 json
【发布时间】:2016-02-12 21:24:38
【问题描述】:

我知道有很多类似的问题,但没有一个对我有帮助。

在服务器上我有方法:

@RequestMapping(value = "/event", method = RequestMethod.POST , produces = MediaType.APPLICATION_JSON_VALUE)
    public void bookOpened(
            @RequestParam(value="id", required = true) int id,
            @RequestParam(value="type", required = true) String type,
            HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {

    }

在客户端我发送一个请求:

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/event');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = function() {
            if (xhr.status === 200) {
                var userInfo = JSON.parse(xhr.responseText);
                console.log(userInfo);
            }
        };
        xhr.send(JSON.stringify({
            id: 1,
            type: 'BOOK_VIEWED'
        }));

请求以错误 400(错误请求)结束,我不知道为什么

【问题讨论】:

    标签: json ajax spring


    【解决方案1】:

    你需要在方法参数中使用@RequestBody注解。有关更多信息,请参见例如:Parsing json into java objects in spring-mvc

    【讨论】:

      猜你喜欢
      • 2015-11-06
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 2013-03-04
      • 2018-06-10
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多