JQuery_JAVA_利用jQuery的AJAX和JSON實現可輸入下拉框提示

 若是實現形如:javascript

的jquery的自動提示下拉框效果能夠採用jquery的插件:FlexBox css

下面對個人一點應用心得與朋友交流下。html

插件下載能夠從這裏:http://flexbox.codeplex.com/java

下載後在FlexBox目錄下有插件的JS文件(jquery.flexbox.js,jquery.flexbox.min.js),這裏我測試使用的是jquery1.3.1版本,在css目錄中有其樣式表文件jquery.flexbox.css:jquery

 

/* Input textbox - do not specify a width here, it will be overwritten */
.ffb-input 
{
	float:left;
	color:#000; /* must specify along with watermark color */
	height:16px; /* required for webkit browsers (Safari, Chrome) */
}
/* Color of watermark, if present */
.ffb-input.watermark { /* added and removed dynamically */
	color:#888; /* must specify along with input color */
}
/* Drop-down arrow, with sprited image */
.ffb-arrow 
{
	float:left;
	width:17px;
	height:22px;
	background-image:url(../img/sel_win7.gif);
}
.ffb-arrow.out { /* css sprite technique */
	background-position:0;
}
.ffb-arrow.over { /* css sprite technique */
	background-position:-17px 0;
}
.ffb-arrow.active { /* css sprite technique */
	background-position:-34px 0;
}
.ffb-no-results 
{
	padding:2px;
	color:#888;
	font-style:italic;
	border-bottom:1px solid #828790;
}
/* Container for dropdown contents */
.ffb {
	position:absolute; /* this guy's parent div is hard-coded to position:relative */
	overflow:hidden;
	border-left:1px solid #828790; /* #7B9EBD for Vista */
	border-right:1px solid #828790;
	background-color:#fff; /* Give it a background-color, so it's not transparent */
}
/* Inner div for dropdown */
.ffb .content {
	overflow:auto;
}
.ffb .content .row {
	border-bottom:1px solid #828790;
	color:#000;
	height:20px;
	clear:both;
}
.ffb-sel {
	cursor:pointer;
	cursor:hand;
	color:#fff !important;
	background-color:#39f;
}
.ffb-match {
	font-weight:bold;
	color:#000;
}

/* Paging */
.ffb .paging {
	vertical-align:middle;
	border-bottom:1px solid #828790;
}
.ffb .page, .ffb a.page {
	font-size:85%;
	padding:2px;
	border:solid 1px #339;
	background-color:#eef;
	margin:2px;
}
.ffb .box {
	width:22px;
	margin:2px;
}
.ffb .summary {
	font-size:85%;
}

在img目錄中有樣式圖片素材:web

插入頁面代碼:json

<mce:script type="text/javascript" src="js/jquery/jquery-1.3.1.js" mce_src="js/jquery/jquery-1.3.1.js"></mce:script>
<mce:script type="text/javascript" src="js/jquery/flexbox/jquery.flexbox.js" mce_src="js/jquery/flexbox/jquery.flexbox.js"></mce:script>

 

在頁面中插入div:緩存

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>.: Fairway Technologies jQuery FlexBox :.</title>
		<link rel="stylesheet" type="text/css" href="../FlexBox/css/jquery.flexbox.css" mce_href="FlexBox/css/jquery.flexbox.css" />

		<mce:script type="text/javascript" src="../FlexBox/js/jquery-1.3.1.js" mce_src="FlexBox/js/jquery-1.3.1.js"></mce:script>
        
		<mce:script type="text/javascript" src="../FlexBox/js/jquery.flexbox.min.js" mce_src="FlexBox/js/jquery.flexbox.min.js"></mce:script>
		<mce:script type="text/javascript" src="js/countries.js" mce_src="js/countries.js"></mce:script>
		<mce:script type="text/javascript"><!--
			$(function() {
				// Setting an initial value, and changing the page size
				$('#ffb6').flexbox(countries, {
					method: 'GET', // 提交數據方式「GET」或是「POST」,必定要注意大小寫;默認GET
					queryDelay: 100, // 查詢延遲,在查詢前的時間毫秒單位;默認爲100毫秒
					allowInput: true, // 是否容許用戶輸入;默認容許
					containerClass: 'ffb',
					contentClass: 'content',
					selectClass: 'ffb-sel',
					inputClass: 'ffb-input',
					arrowClass: 'ffb-arrow',
					matchClass: 'ffb-match',
					noResultsText: 'No matching results', // 沒有數據返回的提示信息
					noResultsClass: 'ffb-no-results', // 沒有數據返回時提示信息的樣式
					showResults: true, // 是否顯示結果
					selectFirstMatch: true, // 是否自動選中第一個結果
					autoCompleteFirstMatch: false, // 是否自動根據第一條數據補充完成
					highlightMatches: true, // 高亮顯示匹配的結果
					highlightMatchesRegExModifier: 'i', // 'i' for case-insensitive, 'g' for global (all occurrences), or combine
					minChars: 1, // 最少輸入字符數
					showArrow: true, // 是否顯示右邊的倒三角,false:形如google提示樣式
					arrowQuery: '', // 當箭頭點擊後查詢(the query to run when the arrow is clicked)
					onSelect: false, // function to run when a result is selected.  this.getAttribute('hiddenValue') gets you the value of options.hiddenValue
					maxCacheBytes: 32768, // 最大緩存字節數,0爲不緩存(in bytes, 0 means caching is disabled)
					resultTemplate: '{name}', // 返回模板 ({id}-{name}則顯示如:12-測試 )html template for each row (put json properties in curly braces)
					displayValue: 'name', // 顯示的值 json element whose value is displayed on select
					hiddenValue: 'id', // 隱藏值 json element whose value submitted when form is submitted
					initialValue: '', // form讀取時的初始值 what should the value of the input field be when the form is loaded?
					watermark: '', // text that appears when flexbox is loaded, if no initialValue is specified.  style with css class '.ffb-input.watermark'
					width: 200, // 下拉框長度 total width of flexbox.  auto-adjusts based on showArrow value
					resultsProperty: 'results', // 返回屬性 用於json的鍵 json property in response that references array of results
					totalProperty: 'total', // 總數屬性,返回的json用來保存總數的鍵,用於分頁 json property in response that references the total results (for paging)
					maxVisibleRows: 0, // 最大可見行數,默認是0,能夠忽略 default is 0, which means it is ignored.  use either this, or paging.pageSize
					paging: {
						style: 'input', // 跳轉頁數輸入格式,默認輸入框或是列表(1,2,3...)or 'links'
						cssClass: 'paging', // 分頁樣式 prefix with containerClass (e.g. .ffb .paging)
						pageSize: 10, // 每頁分頁數若是顯示條數小於這個數則不顯示分頁按鈕 acts as a threshold.  if <= pageSize results, paging doesn't appear
						maxPageLinks: 5, // 最大分頁數字顯示,只對分頁鏈表樣式有做用 used only if style is 'links'
						showSummary: true, // 是否顯示分頁(共 {total}條 當前{page}/{pages}頁)提示信息 whether to show '共 {total}條 當前{page}/{pages}頁' text
						summaryClass: 'summary', // 分頁(共 {total}條 當前{page}/{pages}頁)提示信息的樣式 class for '共 {total}條 當前{page}/{pages}頁', prefix with containerClass
						summaryTemplate: '共 {total}條 當前{page}/{pages}頁' // can use {page} and {pages} as well
					}
				});

			});
		
// --></mce:script>
	</head>
	<body>
		<div id="ffb6"></div>
	</body>
</html>

 

 

在struts後臺獲得傳入的數據能夠是: app

 

String pageIndex = request.getParameter("p");//頁數
String pageSize = request.getParameter("s");//每頁條數
String reqStr = request.getParameter("q");//條件

 

 獲得輸入的條件和分頁數據curl

返回JSON數據

 

response.setContentType("application/json;charset=GBK"); 
		response.setCharacterEncoding("GBK"); 
		PrintWriter pw = response.getWriter();
		Map resMap = null;
		int count = attributeService.getAttrCountByCon(attr);
		if(count > 0){
			List attrList = attributeService.getAttrListByConForPage(attr, page, size);
			List list = new ArrayList();
			for (int i = 0; i < attrList.size(); i++) {
				Object[] dbRes = (Object[])attrList.get(i);
				resMap = new HashMap();
				resMap.put("id",dbRes[0]);
				resMap.put("name",dbRes[1]);
				list.add(resMap);
			}
			resMap = new HashMap();
			resMap.put("results", list.toArray());
			resMap.put("total",new Integer(count));
		}else{
			resMap = new HashMap();
			resMap.put("total",new Integer(0));//數據總數用於分頁
		}
		pw.write(JsonUtil.toJson(resMap));
		pw.flush();

 

 

JSON轉換類代碼: 

 

import java.util.Iterator;
import java.util.Map;

	public final class JsonUtil {
	    public static String toJson(Object o) {
	        if (o==null)
	            return "null";
	        if (o instanceof String)
	            return string2Json((String)o);
	        if (o instanceof Boolean)
	            return boolean2Json((Boolean)o);
	        if (o instanceof Number)
	            return number2Json((Number)o);
	        if (o instanceof Map)
	            return map2Json((Map)o);
	        if (o instanceof Object[])
	            return array2Json((Object[])o);
	        if (o instanceof int[])
	            return intArray2Json((int[])o);
	        if (o instanceof boolean[])
	            return booleanArray2Json((boolean[])o);
	        if (o instanceof long[])
	            return longArray2Json((long[])o);
	        if (o instanceof float[])
	            return floatArray2Json((float[])o);
	        if (o instanceof double[])
	            return doubleArray2Json((double[])o);
	        if (o instanceof short[])
	            return shortArray2Json((short[])o);
	        if (o instanceof byte[])
	            return byteArray2Json((byte[])o);
	        throw new RuntimeException("Unsupported type: " + o.getClass().getName());
	    }

	    static String array2Json(Object[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(toJson(array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String intArray2Json(int[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toString((int)array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String longArray2Json(long[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(Long.toString((long)array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String booleanArray2Json(boolean[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(Boolean.toString((boolean)array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String floatArray2Json(float[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(Float.toString((float)array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String doubleArray2Json(double[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(Double.toString((double)array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String shortArray2Json(short[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(Short.toString((short)array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String byteArray2Json(byte[] array) {
	        if (array.length==0)
	            return "[]";
	        StringBuffer sb = new StringBuffer(array.length << 4);
	        sb.append('[');
	        for (int i = 0; i < array.length; i++) {
				sb.append(Byte.toString((byte)array[i]));
				sb.append(',');
			}
	        // set last ',' to ']':
	        sb.setCharAt(sb.length()-1, ']');
	        return sb.toString();
	    }

	    static String map2Json(Map map) {
	        if (map.isEmpty())
	            return "{}";
	        StringBuffer sb = new StringBuffer(map.size() << 4);
	        sb.append('{');
	        Iterator keys = map.keySet().iterator();
	        while(keys.hasNext()){
	        	Object key = keys.next();
	        	Object value = map.get(key);
	            sb.append('/"');
	            sb.append(key);
	            sb.append('/"');
	            sb.append(':');
	            sb.append(toJson(value));
	            sb.append(',');
	        }
	        // set last ',' to '}':
	        sb.setCharAt(sb.length()-1, '}');
	        return sb.toString();
	    }

	    static String boolean2Json(Boolean bool) {
	        return bool.toString();
	    }

	    static String number2Json(Number number) {
	        return number.toString();
	    }

	    static String string2Json(String s) {
	        StringBuffer sb = new StringBuffer(s.length()+20);
	        sb.append('/"');
	        for (int i=0; i<s.length(); i++) {
	            char c = s.charAt(i);
	            switch (c) {
	            case '/"':
	                sb.append("///"");
	                break;
	            case '//':
	                sb.append("////");
	                break;
	            case '/':
	                sb.append("///");
	                break;
	            case '/b':
	                sb.append("//b");
	                break;
	            case '/f':
	                sb.append("//f");
	                break;
	            case '/n':
	                sb.append("//n");
	                break;
	            case '/r':
	                sb.append("//r");
	                break;
	            case '/t':
	                sb.append("//t");
	                break;
	            default:
	                sb.append(c);
	            }
	        }
	        sb.append('/"');
	        return sb.toString();
	    }
	}
 
相關文章
相關標籤/搜索