【问题标题】:Dynamically generate the content of Drop Down list via jQuery通过jQuery动态生成下拉列表的内容
【发布时间】:2011-01-22 04:06:41
【问题描述】:

我是 Javascript、JSON 和 jQuery 的新手。所以请对我放轻松。我有一个包含下拉列表的 JSP 页面。加载页面时会填充下拉列表的内容。我写了一个Servlet,它以Map的形式返回下拉列表的包含,并将其转换为JSON字符串并通过response.getWriter().write(json);发送回jsp但是我无法从jsp端取回结果,并从结果中填充下拉列表的包含。这是我的代码

customer.jsp

$(document).ready(function() {
  getCustomerOption('customer'); //try to pre-populate the customer drop down list
});

function getCustomerOption(ddId) {
  var dd = $('#' + ddId);
  $.getJSON("http://localhost:8080/WebApps/DDListJASON", function(opts) {
      $('>option', dd).remove(); // Remove all the previous option of the drop down
      if (opts) {
        $.each(opts, function(key, value) {
            dd.append($('<option/>').val(key).text(value));
          }
        }
      });
  }

down where the drop down list is generated

<select id="customer" name="customer">  
    <option></option>  
</select>

结果是没有任何内容填充到列表中。好难过

【问题讨论】:

  • 刚刚更新了代码。现在是正确的。

标签: javascript jquery ajax json drop-down-menu


【解决方案1】:

我认为您在文档就绪中调用了错误的函数

不应该

getInitialOption('customer');

而不是

getCustomerOption('customer');

【讨论】:

    【解决方案2】:

    您可以使用以下代码向&lt;select&gt; 添加额外的&lt;option&gt; 元素:

    $("#selectID").append("<option>" + text + "</option>");
    

    见:JQuery Docs

    【讨论】:

      【解决方案3】:

      我不明白 $(''),但我也不确定这是否是问题所在,很难准确判断。

      我知道,如果您确实在内存中创建选项列表,然后使用 .html(options) 追加一个而不是一次追加一个,那会更快。这也可能更容易理解,一次构建 html 一行然后附加它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-06
        • 1970-01-01
        • 2014-12-10
        • 1970-01-01
        • 1970-01-01
        • 2011-02-23
        • 1970-01-01
        • 2023-03-14
        相关资源
        最近更新 更多