Django中的Jquery下拉列表
我正在学习在Django应用中使用Jquery。我的代码看起来是这样的:
views.py
from django.shortcuts import render
from django.http import HttpResponse
from airapp.models import Travel
def search_form(request):
return render(request, 'search_form.html')
def searchs(request):
if 'tr' in request.GET and request.GET['tr']:
q = request.GET['tr']
books = Travel.objects.filter(froms__icontains=q)
return render(request, 'search_results.html',
{'books': books, 'query': q})
else:
return HttpResponse('Please submit a search term.')
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form id="travel-form">
TRAVEL<select name='tr'>
<option value='one' >ONE WAY</option>
<option value='two'>TWO WAY</option>
</select>
</form>
<div id='one' >
</div>
</body>
</html>
search_results.html
<p>You searched for: <strong>{{ query }}</strong></p>
{% if books %}
<p>Found {{ books|length }} book{{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.froms }}</li>
<li>{{ book.to}}</li>
<li>{{ book.classs }}</li>
<li>{{ book.details }}</li>
{% endfor %}
</ul>
{% else %}
<p>No books matched your search criteria.</p>
{% endif %}
urls.py
from django.conf.urls import patterns, include, url
from air import views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^search-form/$', views.search_form),
url(r'^search/$', views.search),
)
当我从旅行下拉列表中选择一个选项,比如'one'或'two'时,我想在创建表单的同一页面(search_form.html)上显示搜索结果。我可以用jquery来显示吗?有没有人能帮我写这段代码?
1 个回答
当我需要进行一些操作,但又不想重新加载页面时,我会使用JQuery来调用Ajax。通过Ajax,我可以在不离开或重新加载页面的情况下完成相关操作,并在JQuery函数中接收Ajax的响应。这里我给你举个简单的例子,帮助你理解这个基本概念:
JQuery函数,放在你需要的模板中,比如(search_form.html)
function search_results(){
//You have to get in this code the values you need to work with, for example:
var search_type = document.getElementsByName("tr")[0].value //Get the value of the selected option ONE/TWO
$.ajax({ //Call ajax function sending the option loaded
url: "/search_ajax_function/", //This is the url of the ajax view where you make the search
type: 'POST',
data: "search_type="+search_type,
success: function(response) {
result = JSON.parse(response); // Get the results sended from ajax to here
if (result.error) { // If the function fails
// Error
alert(result.error_text);
} else { // Success
for(var i=0;i < result.item_list.length;i++){
//Here do whatever you need with the results, like appending to a result div
$('#result_div').append(result.item_list[i]);
}
}
}
});
}
你要明白,我无法完成代码,因为我不知道你想要什么样的结果,或者你想如何展示这些结果,所以你需要根据自己的需求调整这段代码。
通过JQuery调用的AJAX函数
记得在你的urls.py文件中为这个Ajax函数添加一个网址,比如:
url(r'^/search_ajax_function/?$', 'your_project.ajax.search_ajax', name='search_ajax'),
然后你的AJAX函数就像一个普通的Django视图,但要把这个函数放在ajax.py里,代码如下: from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson
@csrf_exempt
def search_ajax(request):
response = []
if "search_type" in request.GET:
search_type = request.GET['search_type']
else:
return HttpResponse(simplejson.dumps(response))
#Now you have here Search_type and you can do something like
books = Travel.objects.filter(froms__icontains=q)
for item in books:
response.append({'id': item.id, 'name': item.name}) # or whatever info you need
return HttpResponse(simplejson.dumps(response))
这样一来,你就可以在不离开页面的情况下,通过JavaScript接收到一个包含你所查询书籍的列表。在第一个函数中,也就是JavaScript那部分,当你收到Ajax的响应时,你会得到一个像这样的列表:
[{'id':1, 'name':'book1'},{'id':2, 'name':'book2'},{'id':3, 'name':'book3'}]
你可以有一个像这样的div:<div id="result_div" style="display:none"></div>
,当你收到列表后,可以让这个div变得可见,并按照你想要的格式或数据来添加结果。
我知道一开始这可能会让人感到困惑,但一旦你习惯了AJAX,这种在不离开或重新加载页面的情况下进行操作就会变得很简单。
理解的基本步骤大致是这样的:
- 在点击或任何你需要的事件时调用JQuery函数
- JQuery从模板中获取一些值,并通过POST发送给AJAX
- 在AJAX中通过POST接收这些信息
- 在AJAX中像普通的Django视图那样处理你需要的操作
- 将结果转换为JSON格式,并发送回JQuery函数
- JQuery函数接收来自AJAX的结果,然后你可以进行任何需要的操作