Thierry Lam Thierry Lam - 4 months ago 15
Javascript Question

How do I remove the square brackets at the end of a JS variable name during AJAX calls?

I currently have the following javascript array:

var stuffs = ['a', 'b'];


I pass the above to the server code using jQuery's
load
:

var data = {
'stuffs': stuffs
};

$(".output").load("/my-server-code/", data, function() {
});


On the server side, if I print the content of
request.POST
(I'm currently using Django), I get:

'stuffs[]': [u'a', u'b']


Notice the
[]
at the prefix of the variable name
stuffs
. Is there a way to remove that
[]
before it reaches the server code?

Answer

This is default behavior in jQuery 1.4+...if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:

$.ajaxSetup({traditional: true});

Note this affects all requests... which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.

Comments