Jquery ajax populate dropdown with json response data

夙愿已清 提交于 2019-12-02 07:44:06

Heres a fiddle that contains the full answer

HTML:

<select name="breakfast" id="breakfast"></select>
<select name="lunch" id="lunch"></select>
<select name="dinner" id="dinner"></select>

JS:

var data = {"breakfast":[{"09:00:00":"9:00 am"},{"09:30:00":"9:30 am"}],"lunch":        [{"12:00:00":"12:00 pm"},{"12:30:00":"12:30 pm"}],"dinner":[{"19:00:00":"7:00 pm"},{"19:30:00":"7:30 pm"}]};

// Put this code inside of the "done callback"
var $elements = $('#breakfast, #lunch, #dinner');
$.each(data, function (dataKey, dataVal) {
    $elements.each(function(domElKey, domElVal){
        if (dataKey === domElVal.id) {
            $.each(dataVal, function(timeKey,timeVal){
                $.each(timeVal,function(timePropKey, timePropVal){
                $(domElVal).append("<option>"+timePropVal+"</option>");
                });
            })
       }
    });
}); 

A fiddle that contains the answer

Manwal

You could use the $.each() function to loop through the data:

.done(function(data) {
$.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });

})

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

Refrence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!