Updating select box options via jQuery AJAX?

2019-08-09 09:41发布

Is there some type of plugin to do this? The server will return JSON content containing the option labels and values.

I can do this manually, I just wanted to see if there was an easier way.

3条回答
倾城 Initia
2楼-- · 2019-08-09 10:07

Loop through the json and do this on each text/value pair (works cross-browser nicely):

var opt = document.createElement('option');
opt.value = "someValue";
opt.appendChild(document.createTextNode("someText"));
$('#mySelect').append(opt);
查看更多
手持菜刀,她持情操
3楼-- · 2019-08-09 10:16

I literally just loop though the items in the list, and generate the html, before inserting the html into the element. There is probably a plugin now you mention it.

var selectHtml = ''
foreach obj Item in jsonobject.list)
  selecthtml += "<option value="+ item.value +">" + item.label + "</option>"

$('selectList').html(selectHtml);

Or something similar

查看更多
Rolldiameter
4楼-- · 2019-08-09 10:26

I use javascript, jQuery and AJAX way to update the select box with JSON data in the following way. Its pretty clean and concise and does the job perfectly.

$.getJSON(url, data, function(responseJSON){ // GET JSON value from the server
    $("#mySelect option").remove(); // Remove all the <option> child tags from the select box.
    $.each(responseJSON.rows, function(index, item) { //jQuery way of iterating through a collection
        $('#mySelect').append($('<option>')
            .text(item.label)
            .attr('value', item.value));
                });
            });
查看更多
登录 后发表回答