2013-08-22 44 views
0

我在使用下面的JQuery,JSP和Controller來返回在應用程序JSP頁面上更改國家下拉菜單時的城市列表,但我認爲jQuery中的dataType,成功參數不正確因爲我沒有收回清單。那麼有人可以告訴我我在做什麼錯了,以及如何通過更改國家/地區下拉菜單來獲得城市列表以將其添加到城市下拉菜單中?使用JQuery返回一個列表

感謝您的時間

<script type="text/javascript"> 
    function loadCity(){ 
      var countryData="countryId="+$(country).val(); 
      $.ajax({ 
       type: "POST", 
       url: "LoadCities.htm", 
       data:countryData, 
       dataType: "javascript", 
       success: function(cities){ 
        loadCities(eval(cities)) 
       } 
      }); 
     } 

     function loadCities(citiesLst){ 
      clearCitiesDD(); 
      for(var i=0;i<citiesLst.length;i++){ 
       var city=citiesLst[i]; 
       appendCity(city.id,city.value); 
      } 
     } 

     function clearCitiesDD(){ 
      $('#cityDD').find('option').remove(); 
     } 

     function appendCity(id,cityName){ 
      $('#cityDD').append($("<option id='"+id+"'>" + cityName + "</option>")); 
     } 
     }    
</script> 

,並在我的應用程序控制器我有以下代碼:

@RequestMapping(value = "/LoadCities.htm", method = RequestMethod.GET) 
public @ResponseBody 
List<City> getCityByCountryID(HttpServletRequest request, HttpServletResponse response) 
     throws Exception { 

List<City> list= 
icitys.getCitiesByCountry(Long.parseLong(request.getParameter("countryID"))); 
return list;   
} 

,並在JSP文件我有以下的城市和國家下拉菜單:

<tr> 
    <td align="right">Country</td> 
    <td align="left"> 
     <select id ="country" name="country" onchange="loadCity()"> 
      <option value="0">--select--</option> 
      <c:forEach var="countrylst" items="${countriesList}"> 
       <option value="${countrylst.id}">${countrylst.countryName}</option> 
      </c:forEach> 
     </select> 
    </td> 
</tr> 
<tr> 
    <td align="right">City</td> 
    <td align="left"> 
     <select id="cityDD" name="cityDD"> 
      <option value="0">--select--</option> 
     </select>  
    </td> 
</tr> 
+0

您是否在控制檯中檢查了響應,以確保它的格式符合您的預期? –

+0

@RoryMcCrossan檢查了firebug中的響應,但沒有得到任何東西:(這是否意味着我的代碼是正確的?! – MChan

+0

不,這意味着您的JSP中的getCityByCountryID不返回任何內容 –

回答

2

希望你改變$(國家)$('#國)後得到解決。

還有一件事,你把dataType設置爲「javascript」,但可用的數據類型是xml, json, script, or html

更好的嘗試html

祝你好運。

+0

非常感謝,它使用html :) – MChan

0

應該

var countryData="countryId="+$(country).val(); 

var countryData="countryId="+$('#country').val(); 
+0

它已經是var countryData =「countryId =」+ $(country).val();我應該ge國家到#country? – MChan

+0

這就是我的建議。除非某些代碼丟失,否則查詢country元素的jQuery查詢看起來不正確。 –

+0

我已經發布了我在這裏的所有代碼。僅供參考,它已經是沒有#號的國家,如我在我的問題中粘貼的代碼所示 – MChan