Reputation: 441
my ajax function called as
$.ajax({
url:'${pageContext.request.contextPath}'+'/admin/sendMsg',
method:'POST',
traditional: true,
data:{
driverList: JSON.stringify(drivers),
constList: JSON.stringify(constIds),
content: content
},
success: function(data) {
if (data == "FAIL") {
alert("File not found!");
}
},
error: function(request, status, error) {
alert("The request failed: " + request.responseText);
}
});
Where variable "drivers" and "constIds" are array object, output by browser console like
["0", "31", "30"]
0: "0"
1: "31"
2: "30"
length: 3__proto__: Array(0)
My controller:
@ResponseBody
@RequestMapping(value = "/sendMsg", method = RequestMethod.POST)
public void sendMsg(HttpSession session,
@RequestParam(value = "driverList")String[] driverList,
@RequestParam(value = "constList")String[] constList, @RequestParam(value = "content")String content)
{
for (String data : driverList) {
System.out.println("Your Data =>" + data);
}
System.out.println(constList);
}
But the output is
Your Data =>["0"
Your Data =>"31"
Your Data =>"30"]
So how can I get rid of those brackets, then I can parse the string to Integer.
Upvotes: 1
Views: 2989
Reputation: 123
I faced a list of errors, attaching below the final working code..
$.ajax({
type: "POST",
headers: { //Required to avoid 415 error
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: "/item/refresh",
data: JSON.stringify(itemIDs), //itemIDs = ["5", "3", "8"]
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
and at Controller side :
@ResponseBody
@RequestMapping(path = "/item/refresh", method = RequestMethod.POST)
public String BookingItemList(@RequestBody Long[] itemIDs) //RequestBody instead of regular parameter
References : https://stackoverflow.com/a/11549679/557968 https://stackoverflow.com/a/32970230/557968
Upvotes: 0
Reputation: 337560
The brackets are appearing because you are calling JSON.stringify
on the arrays, which is unnecessary. Try this:
$.ajax({
url: '${pageContext.request.contextPath}/admin/sendMsg',
method: 'POST',
traditional: true,
data: {
driverList: drivers,
constList: constIds,
content: content
},
success: function(data) {
if (data == "FAIL") {
alert("File not found!");
}
},
error: function(request, status, error) {
alert("The request failed: " + request.responseText);
}
});
Upvotes: 1