Reputation: 348
I' trying to send some data from the frontend to a Controller in Spring. I am able to recover all the data except for the Integer [] objectIds.
This is my ajax function:
var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });
$.ajax({
type:'POST',
url:'/sendData',
data:{'start':start, 'end':end, 'locale':locale, dataToSend},
async:false,
dataType: "json",
success:function(data){}
});
And this is my Controller function:
@PostMapping(path="/sendData")
public @ResponseBody String sendData(HttpServletResponse response,
@RequestParam(required=true, name="start") String start,
@RequestParam(required=true, name="end") String end,
@RequestParam(required=true, name="locale") Locale locale,
@RequestParam(required=false, name="objectIds") Integer[] objectIds) throws DocumentException, IOException {
//some more code
}
any idea why it's not working??
Upvotes: 0
Views: 364
Reputation: 7624
Problem is in the way you are sending JSON
Case 1: How you are sending
var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });
var mainJSOn = {
'start': "start",
'end': "end",
'locale': "locale",
dataToSend
}
console.log(JSON.stringify(mainJSOn));
OUTPUT:
{"start":"start","end":"end","locale":"locale","dataToSend":"{\"objectIds\":[{\"objectIds\":111},{\"objectIds\":222}]}"}
Case 2: How you should actually send
var dataToSend1 = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend1 = JSON.stringify(dataToSend1 );
var mainJSOn1 = {
'start': "start",
'end': "end",
'locale': "locale",
'objectIds': dataToSend1
}
console.log(JSON.stringify(mainJSOn1));
OUTPUT:
{"start":"start","end":"end","locale":"locale","objectIds":"[{\"objectIds\":111},{\"objectIds\":222}]"}
Look at the Output of Both Cases.
Change your code like done in Case 2
Upvotes: 1
Reputation: 171669
Your are stringifying the wrong object and burying the key objectIds
inside it
Try changing to
var dataToSend = JSON.stringify([{objectIds: 111}, {objectIds: 222}]);
$.ajax({
type: 'POST',
url: '/sendData',
data: {
'start': start,
'end': end,
'locale': locale,
'objectIds': dataToSend
},
// async:false, // NEVER USE THIS!!!!
dataType: "json",
success: function(data) {}
});
Upvotes: 0