获取有关Ajax调用使用JSON一个400错误 [英] Getting a 400 Error on Ajax call with JSON

查看:267
本文介绍了获取有关Ajax调用使用JSON一个400错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道什么是错的,我这样做的方式... 我得到一个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;
    }
 

解决方案

您不会实际发送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) {
        }
});

这篇关于获取有关Ajax调用使用JSON一个400错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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