admin管理员组

文章数量:1183213

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?

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?

Share Improve this question edited Jul 16, 2010 at 15:46 Thierry Lam asked Jul 16, 2010 at 15:39 Thierry LamThierry Lam 46.3k42 gold badges121 silver badges145 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 35

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.

When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.

POST requests work in exactly the same way (unless the json is sent as one long json string).

In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.

I'm not sure how Django parses query strings.

The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django's way of telling you it is an array. You could probably implement your own print function which does not show them.

本文标签: