我正在尝试在 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 search(request):
if 'f' in request.GET and request.GET['f']:
q = request.GET['f']
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.')
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
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
FROM<input type="text" name="f"><br>
TO<input type="text" name="t"><br>
CLASS<input type="text" name="c"><br>
<input type="submit" value="Search">
</form>
</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 %}
当搜索结果显示时,它将显示在一个新的 html 页面(search_results.html)上。我想在单击搜索按钮时在创建表单的同一 html 页面(search_form.html)上显示搜索结果。可以吗使用jquery显示它?谁能帮我写一下代码。 还有人建议我学习 ajax 和 jquery 的好教程以及如何使用它 django 应用程序开发。
最佳答案
这是一个工作示例。只需要修改search_form.html:
<html>
<head>
<title>Search</title>
<script language="JavaScript" type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(function() {
$("#search-form").submit(function() {
var from = $("#search-form :input[name='f']").val();
$.get("/search/", { f : from })
.done(function(data) {
$("#search-result").html(data);
$("#search-result").show();
});
return false;
})});
</script>
</head>
<body>
<form id="search-form">
FROM<input type="text" name="f"><br>
TO<input type="text" name="t"><br>
CLASS<input type="text" name="c"><br>
<input type="submit" value="Search">
</form>
<div id="search-result" style="display:none">
</div>
</body>
</html>
基本上,它的作用是:
- 在 head 中包含 jQuery
- 在脚本中,替换“search-form”的“提交”行为:使用
$.get
向服务器发送 GET 请求,并直接在“search-result”div 中显示响应。 (您可以修改代码以使其更加健壮) - 在正文中,创建一个“搜索结果”div 用于显示响应。默认情况下使其不可见(可以在 CSS 文件中执行)
对于Ajax,您可以引用:http://api.jquery.com/jquery.ajax/ 。 $.get
是基于 $.ajax
的快捷方式:http://api.jquery.com/jquery.get/
关于javascript - Django 中的 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23857878/