1. 程式人生 > 程式設計 >基於JQuery和DWR實現非同步資料傳遞

基於JQuery和DWR實現非同步資料傳遞

後臺我用DWR進行非同步資料傳遞:

程式碼很簡單,就是返回一個數組,如果需求不同可以自己修改:

package org.dwr.re;
/**
 * 測試 返回陣列
 * @author 崔素強
 */
public class BackArray {
	public String[] backArr() {
		String[] arr = new String[] { "堅持","就是","勝利" };
		return arr;
	}
}

前臺記得匯入DWR的JS,和JQuery的JS,然後寫文字框的輸入事件:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>" rel="external nofollow" >  
  <title>自動補全</title>
  <script type='text/javascript' src='/buquan/dwr/util.js'></script>
  <script type='text/javascript' src='/buquan/dwr/engine.js'></script>
  <script type='text/javascript' src='/buquan/dwr/interface/arr.js'></script>
	<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
	<script type="text/javascript">		
	var highlightindex = -1; //高亮節點
	var timeOutId;
	$(document).ready(function() {	
	var wordInput = $("#keyText"); //文字框值	
  var wordInputOffset = wordInput.offset(); //文字框屬性
	//初始時層隱藏,並設定它的樣式,位置
  $("#auto").hide().css("border","1px black solid")
  	.css("position","absolute")
    .css("top",wordInputOffset.top + wordInput.height() + 5 + "px")
    .css("left",wordInputOffset.left + "px")
    .width(wordInput.width() + 5);  
	//文字框事件
	$("#keyText").keyup(function(){
    var myEvent = event || window.event;
    var keyCode = myEvent.keyCode; //取得按鍵的值
		var autoNode = $("#auto");
		//輸入字母等的情況,包括回車,delete
		if (keyCode >= 65 && keyCode <= 90 || keyCode == 8 || keyCode == 46) {
			autoNode.html("");			
			var wordText=$("#keyText").val(); //當前文字框值
			if (wordText != ""){
				//將上一次沒有完成的請求清除
				clearTimeout(timeOutId);
				//將請求延遲
				timeOutId = setTimeout(function(){
					//使用DWR返回資料,暫時沒有設定引數,返回一個字串陣列即可
					arr.backArr(function back(data){
			  		for(i = 0;i < data.length;i++){	
			  			var newDiv = $("<div>").attr("id",i); // 增加標識		  			  			
			  			newDiv.html(data[i]).appendTo(autoNode); //建立新的節點到原DIV元素
			  			//滑鼠移入事件
			  			newDiv.mouseover(function(){
			  				if(highlightindex != -1){
			  					$("#auto").children("div").eq(highlightindex)
			  					.css("background-color","white");
			  				}
			  				//增加一個屬性
			  				highlightindex = $(this).attr("id");
			  				//當前設為紅色
			  				$(this).css("background-color","red");
			  			});
			  			//滑鼠移出事件
			  			newDiv.mouseout(function(){
			  				//當前清除顏色
			  				$(this).css("background-color","white");
			  			});
			  			//滑鼠單擊事件
			  			newDiv.click(function(){
			  				//取出高亮節點的文字內容
				        var comText = $("#auto").hide().children("div").eq(highlightindex).text();
				        highlightindex = -1;
				        //文字框中的內容變成高亮節點的內容
				        $("#keyText").val(comText);
			  			});
			  		}
			  		if (data.length > 0){		  			
			  			autoNode.show();
			  		}else{
			  			autoNode.hide();
			  		}
			  	});
		  	},500); //延遲處理
	  	} else {	  		
		  	autoNode.hide();
	  	}
	  	highlightindex = -1;
  	} else if (keyCode == 38 || keyCode == 40) {
  		if (keyCode == 38) { //向上        
        var autoNodes = $("#auto").children("div")
        if (highlightindex != -1) {
          //如果原來存在高亮節點,則將背景色改稱白色
          autoNodes.eq(highlightindex).css("background-color","white");
          highlightindex--;
        } else {
          highlightindex = autoNodes.length - 1;  
        }
        if (highlightindex == -1) {
          //如果修改索引值以後index變成-1,則將索引值指向最後一個元素
          highlightindex = autoNodes.length - 1;
        }
        //讓現在高亮的內容變成紅色
        autoNodes.eq(highlightindex).css("background-color","red");
      }
  		if (keyCode == 40) { //向下        
        var autoNodes = $("#auto").children("div")
        if (highlightindex != -1) {
          //如果原來存在高亮節點,則將背景色改稱白色
          autoNodes.eq(highlightindex).css("background-color","white");
        }
        highlightindex++;
        if (highlightindex == autoNodes.length) {
          //如果修改索引值以後index變成-1,則將索引值指向最後一個元素
          highlightindex = 0;
        }
        //讓現在高亮的內容變成紅色
        autoNodes.eq(highlightindex).css("background-color","red");
      }
  	} else if (keyCode == 13) {
  		 //下拉框有高亮內容
      if (highlightindex != -1) {
        //取出高亮節點的文字內容
        var comText = $("#auto").hide().children("div").eq(highlightindex).text();
        highlightindex = -1;
        //文字框中的內容變成高亮節點的內容
        $("#keyText").val(comText);
      } else {
        //下拉框沒有高亮內容
        alert("文字框中的[" + $("#keyText").val() + "]被提交了");
      }
  	}
	});
	});
	</script>	
 </head> 
 <body>
  <input type="text" id="keyText" name="keyText" width="50px" />
  <div id="auto" align="left"></div>
 </body>
</html>

當你輸入時,會去後臺查詢並顯示一些資料,你可以使用上下鍵來操作,回車時自動提交資料!

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