在Django下使用Jquery ajax實現select表單的二級聯動__Jquery

來源:互聯網
上載者:User
在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>

最終呈現效果如下:


完結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.