Ajax 实现联动效果


Action函数:

	public void writeAjaxObject(Object data) {
		PrintWriter out = null;
		try {
			out = getResponse().getWriter();
			out.print(data);
			out.flush();			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}

	public String gettrade(){
		List<DataDictionaryItem> trades =  dataDict.getOptions("global","trade",null,"orderno ASC");
		jsonlsunit = new JSONArray(trades);
		writeAjaxObject(jsonlsunit);
		return null;
	}
	
	public String getposition(){
		if (null != trade){
			List<DataDictionaryItem> positions =  dataDict.getOptions("global","trade",trade,"orderno ASC");
			jsonlsunit = new JSONArray(positions);
			writeAjaxObject(jsonlsunit);
		}
		return null;
	}




页面代码:

<select name="specialist.trade" id="trade"  onchange="setPosition(this.options[this.selectedIndex].value);">
</select>

<select name="specialist.position" id="position" ></select>


脚本代码:

	var tradeUrl = "/pub/register!gettrade.hx";	
	var positionUrl = "/pub/register!getposition.hx?trade=";
	
	function setPosition(trade){
		if( trade == null ||trade == ""){
			trade = "0";
		}
		$.getJSON(positionUrl+trade, function(data){
			clearSelect("position");
			$.each(data,function(i,item){
				var position = item.split(",");
				$("#position").append("<option value='"+position[0]+"'>"+position[1]+"</option>");
			});
		});
	}
	function clearSelect(selectId){
		var selectObj = document.getElementById(selectId);
		var len = selectObj.options.length; 
		for (var i=0; i < len; i++){ 
			selectObj.options[0] = null; 
		}
	}
	$(document).ready(
			function setTrade(){
				clearSelect("trade");
				$.getJSON(tradeUrl, function(data){
					$.each(data,function(i,item){
						var trade = item.split(",");
						if(i==0){
							setPosition( trade[0]);
						}
						$("#trade").append("<option value='"+trade[0]+"'>"+trade[1]+"</option>");
					});
				});
			}			
	)
	


当然,还要包括Jquery,我用的是1.3的

你可能感兴趣的:(html,jquery,Ajax,脚本,DWR)