Yahoo UI 之AutoComplete控件

AutoComplete控件有多种使用方式,这里主要讲一下基于Jsonxml方式的使用。

 

一、               基于JSON

所谓基于JSON就是从server端传输数据的表现形式,JSONJavaScript 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就是用冒号分割的可嵌套的键值对。

 

下面我们通过一个例子来说明一下基于JSONAutoComplete的用法

首先,建立一个web project,使用Spring MVC,将Yahoo UI(当前版本 2.3.0 )复制到projectWebRoot目录下,找到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>  

 

下面我们通过一个例子来说明一下基于XMLAutoComplete的用法

首先,在上面的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,由于工程比较大,没有上传成功,所以有想要源码的ggjjddmm们,请发信到我的邮箱:firefly16888@sina.com

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值