У меня есть 3 зависимых выпадающих списка проселочных дорог страны.
, где страна предварительно заполняется из базы данных и на основе выбора первого, во втором отобразятся соответствующие города.
проблема заключается в том, что когда пользователь выбирает страну, город заполняется, но на экране отображается undefined
, но в cmd отображается правильный ответ.
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('/')