2013-04-23 128 views
1

我想從需要JSON的jQuery調用填充下拉列表。我在網上找到下面的代碼是我的出發點(Java和春季3),但我接受其他/更好的方法:jQuery - JSON來填充下拉列表

的JSP(僅顯示相關的代碼):

<script language="JavaScript"> 
      $(document).ready(function() { 
       $('#parkName').change(
       function(){ 
        alert($(this).val()); 
        $.getJSON('${findUnitsURL}', { 
         parkName : $(this).val(), 
         ajax : 'true' 
        }, function(data) { 
         var html = '<option value="">City</option>'; 
         var len = data.length; 
         for (var i = 0; i < len; i++) { 
          html += '<option value="' + data[i].name + '">' 
           + data[i].name + '</option>'; 
         } 
         html += '</option>'; 

         $('#parkUnitTitleAersa').html(html); 
        }); 
       }); 
      }); 
     </script> 


<div id="content"> 

       <form:form method="post" action="mainForm" commandName="mainForm"> 

        <form:select id="parkName" path="parkName"> 
         <form:option value="NONE" label="--- Select ---" /> 
         <form:options items="${parkList}" /> 
        </form:select> 

        <form:select id="parkUnitTitleAersa" path="parkUnitTitleAersa"> 
         <form:option value="NONE" label="--- Select ---" /> 
         <form:options items="${parkUnitList}" /> 
        </form:select> 

        <p class="submit"><input type="submit" name="commit" value="Login"></p> 
        </form:form> 

      </div> 

的Java控制器誰有請求的方法:

@RequestMapping(value = "units", method = RequestMethod.GET) 
    public @ResponseBody List<String> unitsForPark(@RequestParam(value = "parkName", required = true) String parkName) { 
     List<String> l = new ArrayList<String>(); 
     l.add("AA01"); 
     l.add("AA02"); 
     l.add("LA03"); 
     l.add("SG04"); 

     return l; 
    } 

當我在「parkName」下拉列表中選擇一個值時,另一個未填充。使用螢火蟲我得到這個錯誤:

[10:46:39.881] GET http://localhost:8084/SpringBlog/units?parkName=LA&ajax=true [HTTP/1.1 406 No Aceptable 62ms] 

任何想法?謝謝!!

+0

你可以通過腳本顯示服務器完成的實際請求嗎?如果您使用「手動」url來檢索數據,您是否收到您的期望? – ShinTakezou 2013-04-23 09:20:00

+1

[''406'](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7)指向Spring問題,因爲Spring不知道如何創建'JSON'數據視圖,因爲'$ .getJSON'設置頭部'Accept:application/json'。你應該看看Spring的[ContentNegotiatingViewResolver](http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.html)和[MappingJacksonJsonView]( http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/view/json/MappingJacksonJsonView.html) – andyb 2013-04-23 09:20:39

+0

@ShinTakezou:你是什麼意思的「手工「?直接寫入瀏覽器?我已經嘗試過,但它檢索到一個錯誤(我可能沒有正確地做它....)你能告訴我一個例子嗎? – Hauri 2013-04-23 09:40:17

回答

1

406指向Spring問題,因爲Spring不知道如何創建數據的JSON視圖,因爲$.getJSON正在設置標頭Accept: application/json。你應該看看Spring的ContentNegotiatingViewResolverMappingJacksonJsonView

假設你的Spring web應用程序的上下文配置中已經有<mvc:annotation-driven/>了嗎?如果是這樣,那麼運行Spring時Jackson可能不在類路徑中。如果使用Maven,Ivy,Gradle(或其他依賴管理/構建工具),只需手動將其添加到您的類路徑或作爲依賴項。