Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
Thierry Lam Avatar asked Jul 16 '10 15:07

Thierry Lam


1 Answers

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.

like image 50
Nick Craver Avatar answered Sep 21 '22 11:09

Nick Craver