jquery Ajax實現Select動態添加資料,jqueryajax

來源:互聯網
上載者:User

jquery Ajax實現Select動態添加資料,jqueryajax

jquery Ajax實現Select動態添加資料,具體內容如下

1.背景 

最近在工作中,遇到了一個關於select的問題。一般情況下,select下拉框中的資料都是固定的或者直接在jsp中讀取列表值顯示。但是,這次要實現select與別的選項框聯動,也就是要動態添加option資料。查閱了很多資料,終於搞定。下面就分享一下,如何利用jQuery和Ajax實現select動態添加資料。 

2.本文代碼實現的是車輛型號根據車輛品牌聯動顯示的功能。首先,是jsp中的車輛品牌定義,這個很簡單。如下:

<li class="form-row"><span style="white-space:pre"> </span><span class="form-lbl"><i class="tip form-tip">*</i>車系</span> <select class="form-select" name="modelId"> </select></li>

然後,是JS代碼: 

function getModelList(){  var brandId = $("select[name=brandId]").val();  $("select[name=modelId]").empty(); //清空 $.ajax({url:'/getModelList.do', type:"post", data:{ brandId : brandId }, cache: false, error:function(){ },  success:function(data){ var modelList = data.modelList; if(modelList && modelList.length != 0){ for(var i=0; i<modelList.length; i++){  var option="<option value=\""+modelList[i].modelId+"\"";  if(_LastModelId && _LastModelId==modelList[i].modelId){  option += " selected=\"selected\" "; //預設選中  _LastModelId=null;  }  option += ">"+modelList[i].modelName+"</option>"; //動態添加資料  $("select[name=modelId]").append(option); } } } });}

最後,是後台代碼

@RequestMapping("/getModelList") @ResponseBody public Map getModelList(Integer brandId) { List<SrmsModel> modelList = null; try{ modelList = carInfoManager.getSrmsModelListByBrandId(brandId); }catch(Exception e){ LOGGER.error("擷取年租車輛型號異常:{}", e.getMessage()); } Map<String, Object> returnMap = Maps.newHashMap(); returnMap.put("modelList", modelList); return returnMap; }

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.