[英]Jquery drop down list in Django
我正在嘗試在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),
)
當我從旅行下拉列表中選擇一個選項“一個”或“兩個”時,我想在創建表單的同一頁面上顯示搜索結果(search_form.html)。我可以使用jquery顯示它嗎? 誰能幫我寫代碼。
當我需要執行一些操作並且不想重新加載頁面時,我使用對Ajax的JQuery調用,我在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,例如: url(r'^/search_ajax_function/?$', 'your_project.ajax.search_ajax', name='search_ajax'),
然后是您的AJAX函數,就像普通的Django View,但是將此函數從django.core.context_processors從django.views.decorators.csrf導入ajax.py,從django.utils導入csrf_exempt,從django.utils導入csrf_exempt導入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 id="result_div style="display:none"></div>
,當您收到列表時,您可以使div可見並將結果附加所需的格式或數據
我知道這在開始時可能會令人困惑,但是一旦您習慣了AJAX,就可以輕松進行這種操作而無需離開或重新加載頁面。
理解的基礎如下:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.