我正在尝试在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),
)
当我从 TRAVEL 下拉列表中选择一个选项时,一个&#39;或者&#39;两个&#39;我想在创建表单的同一页面上显示搜索结果(search_form.html)。我可以使用jquery显示它吗?任何人都可以帮我编写代码。
答案 0 :(得分:0)
当我需要做一些操作并且我不想重新加载页面时,我使用对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,但是把这个函数添加到ajax.py中 来自django.core.context_processors导入csrf 来自django.views.decorators.csrf import csrf_exempt 来自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 one,当你收到来自AJAX的响应时,你有一个像这样的列表:
[{'id':1, 'name':'book1'},{'id':2, 'name':'book2'},{'id':3, 'name':'book3'}]
所以你可以有一个像<div id="result_div style="display:none"></div>
这样的div,当你收到列表时,你可以看到div并用你想要的格式或数据附加结果
我知道这一开始可能会让人感到困惑,但是一旦习惯了AJAX,这种操作无需离开或重新加载页面就很容易了。
理解的基础是: