Getting a 400 Error on Ajax call with JSON

2019-07-21 06:29发布

问题:

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;
    }

回答1:

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) {
        }
});


回答2:

Is your data part missing quotes? data: { "job_position" : JSON.stringify(38) }

Just a thought.



回答3:

/my_project/rest/runs/1234?token=moo - it's GET request sintax

make
url : '/my_project/rest/runs/1234'
and
data: { "job_position" : JSON.stringify(38) , "token" : "moo"}

so full request look like

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