Thierry Lam Thierry Lam - 1 year ago 89
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

var data = {
'stuffs': stuffs

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

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

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download