D
D
Dominik092017-02-13 10:28:54
JavaScript
Dominik09, 2017-02-13 10:28:54

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')

I process data on successful completion of the operation in views.py:
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("Ошибка! Улица не существует");
            }

Select with options from the Json object is correctly filled in by number, but does not display the correct names. Only undefined. Tell me where I made a mistake, because I leafed through a bunch of docks and observed the syntax everywhere?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2017-02-13
@Dominik09

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("Ошибка! Улица не существует");
        }

S
sim3x, 2017-02-13
@sim3x

https://docs.djangoproject.com/en/1.10/ref/request...
make a print in python before sending - what are you sending there anyway

V
vetsmen, 2017-02-13
@vetsmen

Parse the object first, then just get the value out of it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question