简体   繁体   中英

jquery passing single value arrays via ajax

I've seen a lot of posts about how to pass arrays via ajax in jquery. This is not exactly about those questions. Is the following reasonable behaviour or am I doing something wrong?

I have some simple jquery ...

var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
    url: url,
    data: {
        ids: changedIds
    },
    dataType: "json",
    traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
    window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
    console.log("Submit Fail: ");
});

The changedIds array will end up with 0-N integers in it. I check the .length before the POST so a zero length array is not sent. My question is about what happens when there is only ONE value.

It appears that having a single value array treats the "array" like a plain variable. The HTTP request lists the data as:

ids=123

The target of this ajax call is a .Net ActionResult method that wants an array value. It pouts and throws an exception if it is handed what looks like a plain variable.

I have started checking the array .length and if it is 1 then pushing in a known dummy value so that there are two values for the array. This seems to work -- but is this correct behaviour? Is this the best work-around?

Try serializing your data parameter using JSON.stringify and specifying a contentType of application/json as follows:

var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
    url: url,
    data: JSON.stringify({
        ids: changedIds
    }),
    contentType: "application/json",
    dataType: "json",
    traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
    window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
    console.log("Submit Fail: ");
});

That should convert the JavaScript object into valid JSON and tell the server the type of data that you are sending.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM