AutoComplete控件有多種使用方式,這裏主要講一下基於Json和xml方式的使用。
一、 基於JSON
所謂基於JSON就是從server端傳輸數據的表現形式,JSON是JavaScript Object Notation的縮寫,JSON 作爲一種更輕、更友好的 Web services客戶端的格式(多采用瀏覽器的形式或訪問 REST風格 Web服務的Ajax應用程序的形式)引起了 Web 服務供應商的注意。關於JSON的具體說明請自行查找資料,這裏簡單介紹一下JSON數據的表現形式,參照下面的例子:
{"addressbook": {"name": "Mary Lebow",
"address": {
"street": "
5 Main Street"
"city": "San Diego, CA",
"zip": 91912,
},
"phoneNumbers": [
"619 332-3452",
"664 223-4667"
]
}
}
通過上面的例子,我們發現簡單來說JSON就是用冒號分割的可嵌套的鍵值對。
下面我們通過一個例子來說明一下基於JSON的AutoComplete的用法
首先,建立一個web project,使用Spring MVC,將Yahoo UI(當前版本2.3.0)複製到project的WebRoot目錄下,找到yui/examples/autocomplete目錄下的ac_ysearch_json_clean.html文件,將文件76--79行修改如下:
this.oACDS = new YAHOO.widget.DS_XHR("autoCompleteCtrl.do", ["ResultSet.Result","Title"]);
this.oACDS.queryMatchContains = true;
this.oACDS.scriptQueryAppend = "exec=queryByJSON"; // Needed for YWS
然後,建立AutoCompleteCtrl.java文件,代碼片斷如下:
public ModelAndView queryByJSON(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("url = " + request.getRequestURL() + "?" + request.getQueryString());
String query = request.getParameter("query");
StringBuffer result = new StringBuffer();
result.append("{/"ResultSet/":");
result.append("{");
//result.append("/"totalResultsAvailable/":22000000,");
//result.append("/"totalResultsReturned/":2,");
//result.append("/"firstResultPosition/":1,");
result.append("/"Result/":");
result.append("[");
if (query.toUpperCase().startsWith("F")) {
result.append("{/"Title/":/"foo/",/"Summary/":/"... When foo' is used in connection with bar' it has generally traced.../"},");
result.append("{/"Title/":/"Foo Fighters/",/"Summary/":/"Official site with news, tour dates, discography, store, community, and more/"}");
} else {
result.append("{/"Title/":/"Not Found/",/"Summary/":/"Not Found/"}");
}
result.append("]");
result.append("}");
result.append("}");
System.out.println("response = " + result);
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
pw.write(result.toString());
pw.close();
return null;
}
具體內容請參照source
運行結果如圖;
二、 基於XML
Xml格式如下:
<ResultSet>
<Result>
<Title>foo</Title>
<Summary>When foo' is used in connection with bar' it has generally traced...</Summary>
</Result>
<Result>
<Title>Foo Fighters</Title>
<Summary>Official site with news, tour dates, discography, store, community, and more.</Summary>
</Result>
</ResultSet>
下面我們通過一個例子來說明一下基於XML的AutoComplete的用法
首先,在上面的project中找到yui/examples/autocomplete目錄下的ac_ysearch_xml_clean.html文件,將文件48--82行修改如下:
<!--BEGIN SOURCE CODE FOR EXAMPLE =============================== -->
<form action="http://search.yahoo.com/search" οnsubmit="return YAHOO.example.ACXml.validateForm();">
<h3>Yahoo! Search:</h3>
<div id="ysearchautocomplete">
<input id="ysearchinput" type="text" name="p">
<div id="ysearchcontainer"></div>
</div>
</form>
<script type="text/javascript">
YAHOO.example.ACXml = new function(){
// Instantiate an XHR DataSource and define schema as an array:
// ["Multi-depth.object.notation.to.find.a.single.result.item",
// "Query Key",
// "Additional Param Name 1",
// ...
// "Additional Param Name n"]
this.oACDS = new YAHOO.widget.DS_XHR("autoCompleteCtrl.do", ["Result", "Title", "Summary"]);
this.oACDS.responseType = YAHOO.widget.DS_XHR.TYPE_XML;
this.oACDS.queryMatchContains = true;
this.oACDS.scriptQueryAppend = "exec=queryByXML"; // Needed for YWS
// Instantiate AutoComplete
this.oAutoComp = new YAHOO.widget.AutoComplete("ysearchinput","ysearchcontainer", this.oACDS);
// Display up to 20 results in the container
this.oAutoComp.maxResultsDisplayed = 20;
// Require user to type at least 1 characters before triggering a query
this.oAutoComp.minQueryLength = 1;
// Every key input event will trigger an immediate query...
this.oAutoComp.queryDelay = 0;
// ...or queries will be sent after 3 seconds have passed
// since the last key input event
//this.oAutoComp.queryDelay = 3;
// Do not automatically highlight the first result item in the container
this.oAutoComp.autoHighlight = false;
// Enable a drop-shadow under the container element
this.oAutoComp.useShadow = true;
// Enable an iFrame shim under the container element
this.oAutoComp.useIFrame = true;
this.oAutoComp.formatResult = function(oResultItem, sQuery) {
return oResultItem[0] + " (" + oResultItem[1] + ")";
};
// Stub for AutoComplete form validation
this.validateForm = function() {
// Validation code goes here
return true;
};
};
</script>
<!--END SOURCE CODE FOR EXAMPLE =============================== -->
然後,在AutoCompleteCtrl.java文件中,添加如下代碼:
public ModelAndView queryByXML(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("url = " + request.getRequestURL() + "?" + request.getQueryString());
String query = request.getParameter("query");
StringBuffer result = new StringBuffer();
result.append("<ResultSet>");
if (query.toUpperCase().startsWith("F")) {
result.append("<Result>");
result.append("<Title>foo</Title><Summary>... When foo' is used in connection with bar' it has generally traced...</Summary>");
result.append("</Result>");
result.append("<Result>");
result.append("<Title>Foo Fighters</Title><Summary>Official site with news, tour dates, discography, store, community, and more</Summary>");
result.append("</Result>");
} else {
result.append("<Result>");
result.append("<Title>Not Found</Title><Summary>Not Found</Summary>");
result.append("</Result>");
}
result.append("</ResultSet>");
System.out.println("response = " + result);
response.setContentType("text/xml");
PrintWriter pw = response.getWriter();
pw.write(result.toString());
pw.close();
return null;
}
具體內容請參照source
運行結果如圖;
該例子是用eclipse做的,後臺使用spring,