2010-03-01 58 views
2

我是Javascript,JSON和jQuery的新手。所以請容易對我。我有一個包含下拉列表的JSP頁面。下載列表的內容在頁面加載時填充。我寫了一個Servlet,它以Map的形式返回下拉列表的內容,並將其轉換爲JSON字符串並通過response.getWriter().write(json);發送回jsp。但是,我無法從jsp端獲得結果,並且填充從結果中包含下拉列表。這裏是我的代碼通過jQuery動態生成下拉列表的內容

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> 

結果沒有得到填充到列表中。如此悲傷

+0

剛剛更新了代碼。現在是正確的。 –

回答

4

我認爲你正在調用的文件準備

當不可錯功能它是

getInitialOption('customer'); 

而不是

getCustomerOption('customer'); 
+0

我可能是這個世界上最愚蠢的孩子 –

0

您可以添加額外的<option>元素的<select>與代碼:

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

見:JQuery Docs

0

我不明白$(''),但我不確定這是否是問題,很難說清楚。

我知道如果您在內存中創建選項列表,然後使用.html(選項)添加一個附加項,而不是一次追加一個選項,則會更快。這可能使得它更易於理解,一次構建一行html,然後附加它。