如何使用django和ajax在dropdownlist中显示结果

时间:2019-02-27 12:06:17

标签: jquery html ajax django dropdownbox

我有3个依赖下拉列表的乡村城市之路。

从数据库中预先填充国家/地区,然后根据第一个国家/地区的选择显示相关城市。

问题在于,当用户选择一个国家/地区时,会填充城市,但道路显示未定义

在cmd中它仍显示正确答案。

template displayed as html page

cmd display the correct results

models.py

from django.db import models


class Road(models.Model):
    name = models.CharField(max_length=50)
    city = models.ForeignKey("City", on_delete=models.CASCADE, related_name='roads')

    def __str__(self):
        return str(self.name)


class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey("Country", on_delete=models.CASCADE, related_name='cities')

    def __str__(self):
        return str(self.name)


class Country(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return str(self.name)

home.html


<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
        <script>$(document).ready(function(){
                 $('select#selectcountries').change(function () {
                     var optionSelected = $(this).find("option:selected");
                     var valueSelected  = optionSelected.val();
                     var country_name   = optionSelected.text();


                     data = {'cnt' : country_name };

                     $.ajax({
                         type:"GET",
                         url:'/getCity',
                         // data:JSON.stringify(data),
                         data:data,
                         success:function(result){
                            console.log(result);
                            $("#selectcities option").remove();
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectcities").append('<option>'+ result[i].name +'</option>');
                            };
                          },
                    });
                });

                $('select#selectcities').change(function () {
                     var optionSelected = $(this).find("option:selected");
                     var valueSelected  = optionSelected.val();
                     var city_name   = optionSelected.text();


                     data = {'ct' : city_name };

                     $.ajax({
                         type:"GET",
                         url:'/getRoads',
                         // data:JSON.stringify(data),
                         data:data,
                         success:function(result){
                            console.log(result);
                            $("#selectroads option").remove();
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectroads").append('<option>'+ result[i].Vil +'</option>');
                            };
                          },
                    });
                }); 
            });

        </script>
    </head>
    <body>
        <select name="selectcountries" id="selectcountries">
            {% for item in countries %}

            <option val="{{ item.name }}"> {{ item.name }} </option>    
            {% endfor %}

        </select>
        <select name ="selectcities" id="selectcities"></select>
        <select name ="selectroads" id="selectroads"></select>
    </body>
</html>

views.py

from django.shortcuts import render, redirect
from map.models import *
import json as simplejson
from django.http import HttpResponse


# Create your views here.


def index(request):
    countries = Country.objects.all()
    print(countries)
    return render(request, 'home.html', {'countries': countries})


def getCity(request):
    if request.method == 'GET' and request.is_ajax():
        # country_name = request.POST['country_name']
        # country_name = request.GET['cnt']
        country_name = request.GET.get('cnt', None)
        print("ajax country_name ", country_name)

        result_set = []
        all_cities = []

        answer = str(country_name[1:-1])

        print('answer = ', answer)
        selected_country = Country.objects.get(name=answer)
        print("selected country name ", selected_country)

        all_cities = selected_country.cities.all()
        print("cities are: ", all_cities)
        for city in all_cities:
            print("city name", city.name)
            result_set.append({'name': city.name})

        return HttpResponse(simplejson.dumps(result_set), content_type='application/json')
        # return JsonResponse(result_set,status = 200)

    else:
        return redirect('/')


def getRoads(request):
    if request.method == 'GET' and request.is_ajax():
        city_name = request.GET.get('ct', None)
        print("ajax city_name ", city_name)

        result_set = []
        all_roads = []

        # answer = str(city_name[1:-1])
        answer = str(city_name)
        print('answer = ', answer)
        selected_city = City.objects.get(name=answer)
        print("selected city name ", selected_city)

        all_roads = selected_city.roads.all()
        print("roads are: ", all_roads)
        for road in all_roads:
            print("road name", road.name)
            result_set.append({'name': road.name})

        return HttpResponse(simplejson.dumps(result_set), content_type='application/json')
        # return JsonResponse(result_set,status = 200)

    else:
        return redirect('/')

1 个答案:

答案 0 :(得分:1)

错字

Contexto: Acessar a página de bonificação do LPP
* que o usuário "usuario_simples" esteja logado no portal de parceiro
* que esteja na página de bonificação do portal