获取有关Ajax调用使用JSON一个400错误错误、Ajax、JSON

由网友(心碎無痕)分享简介:我不知道什么是错的,我这样做的方式...我得到一个400错误说这是一个错误的请求,但我找不到什么毛病我的语法。$。阿贾克斯({网址:'?/ MY_PROJECT / REST /运行/ 1234令牌=哞',键入:POST,数据:{job_position:JSON.stringify(38)},的contentTyp...

我不知道什么是错的,我这样做的方式... 我得到一个400错误说这是一个错误的请求,但我找不到什么毛病我的语法。

  $。阿贾克斯({
        网址:'?/ MY_PROJECT / REST /运行/ 1234令牌=哞',
        键入:POST,
        数据:{job_position:JSON.stringify(38)},
        的contentType:应用/ JSON的,
        数据类型:JSON,
        成功:函数(HTML){
        }
    });
 

接收控制器:

  @RequestMapping(值=/运行/ {用户id},方法= RequestMethod.POST,消耗= {应用/ JSON})
    公共@ResponseBody布尔在myMethod(@PathVariable字符串userid,@RequestParam(令牌)字符串authenticationToken,@RequestBody @Valid龙job_position){
        返回true;
    }
 

解决方案 AJAX JSON之讲解

您不会实际发送JSON在您的要求,jQuery将你的对象转换为查询字符串。为prevent这个字符串化它自己。

  $。阿贾克斯({
        网址:'/ MY_PROJECT / REST /运行/ 1234',
        键入:POST,
        数据:JSON.stringify({job_position:38,令牌:'哞哞'}),
        的contentType:应用/ JSON的,
        数据类型:JSON,
        成功:函数(HTML){
        }
});
 

I'm not sure what's wrong with the way I'm doing this... I get a 400 Error saying it's a bad request, but I can't find anything wrong with my syntax.

$.ajax({
        url : '/my_project/rest/runs/1234?token=moo',
        type : 'POST',
        data: { job_position : JSON.stringify(38) },
        contentType: 'application/json',
        dataType: 'json',
        success : function(html) {
        }
    });

The receiving controller:

@RequestMapping(value="/runs/{userId}", method = RequestMethod.POST, consumes = {"application/json"})
    public @ResponseBody boolean myMethod(@PathVariable String userId, @RequestParam("token") String authenticationToken, @RequestBody @Valid Long job_position){
        return true;
    }

解决方案

Your not actually sending JSON in your request, jQuery will convert your object to a query string. To prevent this stringify it yourself.

$.ajax({
        url : '/my_project/rest/runs/1234',
        type : 'POST',
        data: JSON.stringify({ job_position : 38, token: 'moo' }),
        contentType: 'application/json',
        dataType: 'json',
        success : function(html) {
        }
});

阅读全文

相关推荐

最新文章