Reputation: 843
here is my code:
urls.py:
from django.conf.urls import patterns
from views import show,showpage
urlpatterns = patterns('',
(r'^$',showpage),
(r'^show/$',show),
)
views.py
from django.http import HttpResponse
def show(request):
arr = reqeust.GET.get('arr','Nothing')
print arr#**it's 'Nothing'**
if arr == 'Nothing':
msg = 'fail'
else:
msg = 'pass'
return HttpResponse(msg)
def showpage(request):
html = ''' <html>
<head>
<script language="javascript" type="text/javascript" src="/site_media/js/jquery-1.7.2.js"></script>
</head>
<body>
<input type="button" id="input_btn"/>
</body>
<script language="javascript" type="text/javascript">
$(function(){
$("#input_btn").bind("click",function(){
arr = [1,2,3,4,5,6]
$.ajax({
type:"GET",
url:"/show/",
data:{arr:arr},//**I want pass the arr to django**
success:function(data){alert(data);},
error:function(data){alert(data);}
});
});
})
</script>
</html>'''
return HttpResponse(html)
when I access localhost:8000,and click the button,I got 'Nothing' printed in the backend console,as you know I got message 'fail' in the frontend
uh..can anybody sovle this problem,I want get the code (arr = reqeust.GET.get('arr','Nothing')
) which return a list([1,2,3,4,5,6]
) or something like this
---------append1-------
I got this in the console when I click the btn
[12/Jun/2012 09:48:44] "GET /show/?arr%5B%5D=1&arr%5B%5D=2&arr%5B%5D=3&arr%5B%5D=4&arr%5B%5D=5&arr%5B%5D=6 HTTP/1.1" 200 4
---------apend2-------
I fixed my code like this:
arr = request.GET.get('arr[]','Nothing')
and I got 6 which is the last one of the javascript array,how can I get the whole array?
thanks advance!
Upvotes: 5
Views: 3298
Reputation: 33420
You can also set:
$.ajaxSettings.traditional = true;
This will make jQuery behave according to the actual HTTP standard, which works with Django.
This is required when you're not going to access request.GET or request.POST yourself (ie. ajax-posting a form).
It's definitively recommended to set this in every django project.
Upvotes: 5
Reputation: 799310
jQuery has decided to add square brackets to the field name, most likely to accommodate PHP. They aren't required for Django, but whatever. Access request.GET['arr[]']
and request.GET.getlist('arr[]')
instead.
Upvotes: 9