通过jQuery AJAX更新选择框选项?

时间:2009-06-24 18:51:33

标签: jquery ajax plugins

是否有某种类型的插件可以执行此操作?服务器将返回包含选项标签和值的JSON内容。

我可以手动执行此操作,我只想查看是否有更简单的方法。

3 个答案:

答案 0 :(得分:2)

循环遍历json并在每个文本/值对上执行此操作(很好地跨浏览器工作):

var opt = document.createElement('option');
opt.value = "someValue";
opt.appendChild(document.createTextNode("someText"));
$('#mySelect').append(opt);

答案 1 :(得分:1)

我只是循环查看列表中的项目,并在将html插入元素之前生成html。现在你提到它可能有一个插件。

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

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

或类似的东西

答案 2 :(得分:0)

我使用javascript,jQuery和AJAX方式以下列方式用JSON数据更新选择框。它非常干净简洁,完美地完成了工作。

$.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));
                });
            });