Answer the question
In order to leave comments, you need to log in
How to properly populate select with options from Json object?
Hello. Unable to display json object values correctly.
From django to views.py I pass it this way:
objects_list = serializers.serialize('json', City.objects.filter(street__icontains=request.POST.get("street"),))
return HttpResponse(json.dumps(objects_list), content_type='application/json')
success: function(data) {
var streets = jQuery.parseJSON(data); // парсирую в объект скрипта
alert(JSON.stringify(streets.street)); // выводит "undefined"
var opts;
for (var id in streets) {
opts += "<option value='" + id + "'>" + JSON.stringify(streets[id].street) + "</option>";
}
document.getElementById('street').innerHTML = opts;
},
error: function(){
alert("Ошибка! Улица не существует");
}
Answer the question
In order to leave comments, you need to log in
success: function(data) {
var streets = jQuery.parseJSON(data),
opts = '';
console.log(streets); // вывод переменной в консоль браузера
// перебор js объекта
for (var key in streets) {
if (!streets.hasOwnProperty(key)) continue;
var street = streets[key];
opts += "<option value='" + street.id + "'>" + street.street + "</option>";
}
},
error: function(){
alert("Ошибка! Улица не существует");
}
https://docs.djangoproject.com/en/1.10/ref/request...
make a print in python before sending - what are you sending there anyway
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question