Problem with ajax/jquery and django
I want to send a value to the server.I send it using:
$.post("http://127.0.0.1:8000/开发者_如何转开发search/",{'long':"30"});
and my views.py is:
def search(request):
lon = request.POST.get('long','')
place = Places.objects.filter(longtitude__icontains=lon)
if place is not None:
return render_to_response('sr.html', {'place': place, 'query': lon})
else:
return HttpResponse("NOTHING FOUND")
But i can not get my database searched for places with longitude containing 30!!!!
filter()
returns a queryset, not an individual item. So the variable you have called place
will not be a Places object, but a queryset containing one or more places.
If for example your template has something like {{ place.name }}
, that will print nothing because a queryset does not have a name
attribute.
Assuming that there will end up being several Places with the same longitude, you will need to iterate through the queryset in your template with a {% for place in places %}
loop.
Have you made sure you are even calling the function?
I would try printing out each value, including place. Since Place.objects.filter can't return None, you should be getting some kind of query set, even if it's empty.
Honestly this code is pretty buggy in general...It would help to know if Places.longtitude is really a string, if it is a string why did you decide to do that?
since place can never be None, did you want to check for an empty queryset in which case you would write
if not place:
I think we need more information then you've given us to help you at all.
DR is spot on, but is missing a little thing. When you do this call in jQuery, you get one huge disadvantage, you can't use the Django template language. When you write a normal view, you would do exactly like DR explained. However since you are doing this with javascript, there are two things you want to do.
- Since you can't rely on Django's auto escaping you need to manually escpape user inputted values like
place.name
. - The data you return, will need to be returned in JSON. This is not stricly necessary, but it will make it a lot easier for you to handle the data in your javascript. Django comes with the simplejson library, that you can fall back on, but I would recommend using the json library, which you can use to easily convert the python objects to json.
remove the ' around long in the jquery
$.post("http://127.0.0.1:8000/search/",{'long':"30"});
should be
$.post("http://127.0.0.1:8000/search/",{long:"30"});
your view is never seeing that 'long' is in the request. using the jquery post method and django together can get confusing, because the stuff between {} is structured differently.
精彩评论