我有一个ajax脚本,使用 GET方法将下拉列表中的选定选项发送到django函数,我以 json格式
发送数据问题一旦我从下拉列表中选择一个选项,就会显示以下错误:
文件“ C:\ Users \ LT GM \ Desktop \ test2ForImportExport \ test2 \ testpro \ views.py“,第30行,在 细节 answer = str(country_name [1:-1])TypeError:“ NoneType”对象不可下标
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.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 };
alert(country_name);
$.ajax({
type:"GET",
url:'/getdetails',
data:JSON.stringify(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>');
};
},
});
});
});
</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>
def home2(request):
countries = country.objects.all()
print(countries)
return render(request, 'home2.html',{'countries': countries})
def getdetails(request):
if request.method == 'GET' and request.is_ajax():
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.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),content_type='application/json')
else:
return redirect('/')
答案 0 :(得分:0)
您已将数据作为JSON发送,而不是作为常规查询数据发送,因此它不在request.GET['cnt']
中。
最简单的方法是从JS中删除该JSON.stringify
调用,因此ajax调用的参数将仅为data: data
。