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?
3 Answers
Reset to default 35This 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.
本文标签:
版权声明:本文标题:javascript - How do I remove the square brackets at the end of a JS variable name during AJAX calls? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738251849a2071409.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论