在Django下使用Jquery ajax實現select表單的二級聯動
採用Django+Jquery實現:
網上也看到很多例子,綜合很多例子,經過嘗試,實現一個簡單的省市二級聯動,記下來,以免忘記,有考慮不嚴謹的地方還請大家指正:
首先是模型設計(資料庫設計):
# coding:utf-8from django.db import models# Create your models here.#省份表class Province(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name#城市表class City(models.Model): name = models.CharField(max_length=40) province = models.ForeignKey(Province) def __unicode__(self): return self.name#這個主要是用來顯示,選擇的結果class SelectP(models.Model): province = models.ForeignKey(Province) city = models.ForeignKey(City)
為此使用了form
# coding:utf-8from django import formsfrom .models import SelectPclass SelectForm(forms.ModelForm): class Meta: model = SelectP fields = '__all__'
以下是views代碼:
# coding:utf-8from django.shortcuts import render_to_response, get_object_or_404, redirect, urlresolvers, RequestContextfrom django.core import serializersfrom django.http import HttpResponsefrom .models import Province, SelectPfrom .forms import SelectForm# Create your views here.#擷取首頁def index(request): if request.method == 'POST': form = SelectForm(request.POST) if form.is_valid(): form.save() return redirect(urlresolvers.reverse('select:select_index')) else: return HttpResponse('error') else: pro = Province.objects.all() se = SelectP.objects.all() return render_to_response('ajaxselect/index.html', {'province':pro,'select':se}, context_instance=RequestContext(request))#ajax擷取資料def getdata(request): pk = request.GET['pk'] province = get_object_or_404(Province, pk=pk) citys = province.city_set.all() data = serializers.serialize('json', citys) return HttpResponse(data, content_type='application/json')
url如下:
urlpatterns = patterns('apps.ajaxselect.views', url(r'^index/$','index', name='select_index') , url(r'^getdata/$', 'getdata', name='getdata') )
通過頁面的連結測試json資料如下所示:
[{"pk": 3, "model": "ajaxselect.city", "fields": {"province": 2, "name": "\u6210\u90fd"}}, {"pk": 4, "model": "ajaxselect.city", "fields": {"province": 2, "name": "\u7ef5\u9633"}}, {"pk": 5, "model": "ajaxselect.city", "fields": {"province": 2, "name": "\u4e50\u5c71"}}]
對此模板頁面設計如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> <script src ="/static/jquery/jquery-2.1.4.min.js"></script> <script src = "/static/bootstrap/js/bootstrap.min.js"></script> <script src="/static/jquery/jquery.form.js"></script></head><body>{% block content %} <form class="form-horizontal" action="{% url 'select:select_index' %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_province" class="control-label">選擇省市</label> <select class="form-control" id="id_province" name="province"> <option selected="selected">請選擇</option> {% for foo in province %} <option value="{{ foo.id }}">{{ foo.name }}</option> {% endfor %} </select> </div> <div class="form-group"> <label for="id_city" class="control-label">選擇城市</label> <select class="form-control" id="id_city" name="city"> <option selected="selected">請選擇</option> </select> </div> <div class="form-group"> <input type="submit" value="提交"> </div> </form> <table class="table table-bordered"> <thead> <tr> <th>省</th> <th>市</th> </tr> </thead> <tbody> {% for foo in select %} <tr> <td>{{ foo.province.name }}</td> <td>{{ foo.city.name }}</td> </tr> {% endfor %} </tbody> </table> <script> $('#id_province').change(function(){ var id = $('#id_province').val(); $.getJSON("{% url 'select:getdata' %}?pk="+id, function(data,textStatus){ var content=''; $.each(data, function(i, item){ content+='<option value='+item.pk+'>'+item.fields.name+'</option>' }); $('#id_city').html(content) }); }); </script></body></html>
最終呈現效果如下:
完結