$.ajax POST/non post behaviour difference?
I am attempting to send some data via JSON to a MVC controller action:
For some reason, this works:
var items = [];
$("input:checked").each(function () { items.push($(this).val()); });
//This works
$.ajax({
type: "POST",
url: url,
data: { listofIDs: items, personID: personID},
dataType: "json",
traditional: true,
success: function() {
//Rebind grid
}
});
//This listofIDs is ALWAYS null !? (longhand for `$.getJSON` ?)
$.ajax({
url: url,
dataType: 'json',
data: { listofIDs: items, personID: personID },
success: function () {
//Rebind grid
}
});
开发者_开发百科
So why does it work at the top, but the bottom it is always null? The same code is used to build items
!?
edit: controller method
public ActionResult AddJson(List<int> listofIDs, int personID)
{
if (listofIDs==null || listofIDs.Count < 1)
return Json(false, JsonRequestBehavior.AllowGet);
...
//Add something to database
//Return true if suceeed, false if not
}
edit: so I ended up solving it by just turning the array into a string and sending it that way. That way I was able to send more than just the array variable.
var items = $(':input:checked').map(function () { return $(this).val();}).toArray();
var stringArray = String(items);
$.ajax({
url: url,
dataType: 'json',
data: { listOfIDs: stringArray, personID: personID },
success: function () {
//rebind grid
}
});
Note no POST
type needed to be set.
Without type: "POST"
it defaults to GET
(according to the docs), which your server side code is probably not expecting.
Also, you could get a list of the values with...
var items = $(':input:checked').map(function() {
return $(this).val();
}).toArray();
jsFiddle.
Not sure if it's better though. Just an idea I had :)
The problem is probably on the server side. In the first case you are using HTTP POST in the other HTTP GET. That means that you probably have to access the data differently. Maybe have a look at Get individual query parameters from Uri for the HTTP GET case.
You're not specifying the type of the request, so it defaults to GET
.
From jQuery Docs:
The type of request to make ("POST" or "GET"), default is "GET".
Perhaps you meant to specify POST
. If you send it using GET the array will be added into the QUERY_STRING
like ?listofIDs=...
and won't be accessible the same way you normally access POSTed data.
精彩评论