Jquery ajax populate dropdown with json response data

后端 未结 2 1872
天涯浪人
天涯浪人 2021-01-23 11:30

I know there are quite a few questions floating on this but I\'m still not sure what to do.

I have a HTML form called \"CuisineForm\", after the user selects the type o

相关标签:
2条回答
  • 2021-01-23 11:56

    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

    0 讨论(0)
  • 2021-01-23 12:01

    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

    0 讨论(0)
提交回复
热议问题