我有一个网页,其中包含2个链接的下拉列表国家和城市,其中,根据第一个下拉菜单的选择,第二个下拉列表显示城市所属的国家/地区。
问题在于第一个下拉列表正在显示从数据库中获取的数据,但是第二个仍然为空。并且系统显示以下错误:
从django.utils将json导入为simplejson ImportError:无法 从“ django.utils”导入名称“ json”
from django.db import models
class country(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return str(self.name)
class city(models.Model):
name = models.CharField(max_length=100)
MouhafazatID = models.ForeignKey(country,on_delete=models.CASCADE)
def __str__(self):
return str(self.name)
from django.contrib import admin
from django.urls import path, include
from.views import *
urlpatterns = [
path('admin/', admin.site.urls),
# path('', home),
path('', home2),
path('getdetails/', getdetails),
from django.shortcuts import render
from django.http import HttpResponse
from testapp.models import *
from django.utils import json as simplejson # i think this is the error?
def home2(request):
countries = country.objects.all()
print(countries)
return render(request, 'home2.html',{'countries': countries})
def getdetails(request):
#country_name = request.POST['country_name']
country_name = request.GET['cnt']
print ("ajax country_name ", country_name)
result_set = []
all_cities = []
answer = str(country_name[1:-1])
selected_country = country.objects.get(name=answer)
print ("selected country name ", selected_country)
all_cities = selected_country.city_set.all()
for city in all_cities:
print ("city name", city.name)
result_set.append({'name': city.name})
return HttpResponse(simplejson.dumps(result_set), mimetype='application/json', content_type='application/json')
<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('/getdetails',data,function(result){
console.log(result);
$("#selectcities option").remove();
for (var i = result.length - 1; i >= 0; i--) {
$("#selectcities").append('<option>'+ result[i].name +'</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>
</body>
</html>
答案 0 :(得分:0)
我能够通过更改
来解决此问题from django.utils import json as simplejson
至
import json as simplejson