1. 程式人生 > >Jquery+Ajax實現Select動態新增資料

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;
	}