应与需求,需要实现一个类似百度输入提示的那种效果。然而这个项目有这样的需求,原因是因为本来原来的数据库数据很乱,接到这个项目后对数据进行了加工,但是肯定会出现人名重复的问题,然而为了检索的唯一性,所有得动态取得用户输入的人名的authorsid,话不多说,常见的有2种方式。中间遇到一些问题,在次分享。

 

1、基于DIV的。

 ①html代码(不在此全部贴出,需要的js会在附件中)

<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/autoquery.js"></script>
<script type="text/javascript" src="scripts/jquery.min.js"></script>


 <input name="searchStr" id="searchStr" type="text" class="k" style="width: 220px;" οnblur="javascript:hideBox();" οnkeyup="javascript:queryMsg();" />
 <input type="hidden" name="authorsid" id="authorsid" value="<%=(null==request.getParameter("authorsid")) ? "" :request.getParameter("authorsid") %>" />

<p><input type="radio" name="searchCon" value="bookname" checked="checked">书名</p>
     <p><input type="radio" name="searchCon" value="timing">题名</p>
     <p><input type="radio" name="searchCon" value="zhuanjizerenzhe">原作者</p>
     <p><input type="radio" name="searchCon" value="authorName" >书评作者</p>
     <p><input type="radio" name="searchCon" value="publishYear">出版年</p>
     <p><input type="radio" name="searchCon" value="isbn">ISBN</p>
     <p><input type="radio" name="searchCon" value="keywords">英文主题词</p>
     <p><input type="radio" name="searchCon" value="bookreviewCon">关键词(全文)</p>


<div id="searchKcResult" class="searchResult"></div>(放最后,js里面差的自己看着办,我用着没问题)

②java代码统一在后面拿出来,差不多是一样的。微笑区别

原理说明:这种实现方式是最容易想到的,如果你jquery用得不熟悉,比如我.当然在代码实现上来看,有些自己写不出来,是别人给我的一个插件,(会用就行,不一定是得非要自己能写,"会用就行")。

2、基于jquery autocomplete

①Html代码


<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<link rel="stylesheet" href="js/jquery.autocomplete.css" type="text/css"></link>

 <input name="searchStr" id="searchStr" type="text" class="k" style="width: 220px;"
               οnkeyup="javascript:query();"/>
              
    <input type="hidden" name="authorsid" id="authorsid" value="<%=(null==request.getParameter("authorsid")) ? "" :request.getParameter("authorsid") %>" />
     <p><input type="radio" name="searchCon" value="bookname" checked="checked">书名</p>
     <p><input type="radio" name="searchCon" value="timing">题名</p>
     <p><input type="radio" name="searchCon" value="zhuanjizerenzhe">原作者</p>
     <p><input type="radio" name="searchCon" value="authorName" >书评作者</p>
     <p><input type="radio" name="searchCon" value="publishYear">出版年</p>
     <p><input type="radio" name="searchCon" value="isbn">ISBN</p>
     <p><input type="radio" name="searchCon" value="keywords">英文主题词</p>
     <p><input type="radio" name="searchCon" value="bookreviewCon">关键词(全文)</p>

②JS代码


function query(){
 var searchCon = $("input[name='searchCon']:checked").val();
 var searchStr=$("#searchStr").val();
 if(searchStr!="" && searchCon=="authorName"){
  $.getJSON("display!findListAuthorByName.action",{"searchCon":searchCon,"authorName":encodeURI(searchStr)}, 

//encodeURI 处理传递参数是中文的问题,当然在服务器端也要做处理
   function(data){
    $('#searchStr').autocomplete(data, {
    max : 12, //参数不再说明,一搜一大把
    minChars : 1,
    width : 225,
    scrollHeight : 300,
    matchContains : true,
    autoFill : true,
    type: "json",
    parse : function (data){

//次方法是解析服务器端返回JSON格式的数据 我服务器端返回的就是JSON格式 所以用的是$.getJSON,如果不套在$.getJSON中,则服务器端返回的是将以行的形式,自己写的时候不知道如何解析,在此只写了json格式
     var rows=[];
     for(var i=0;i<data.length;i++){
      rows[rows.length]={
       data:data[i].cname+" "+data[i].officer+" "+data[i].keshi,
       value : data[i].cname,
       result : data[i].authorsid
      };
     }
     return rows;
    },
    formatItem : function(row, i, max) {
     return row.cname + " " + row.officer +" "+ row.keshi;
    },
    formatMatch : function(row, i, max) {
     return row.cname +" "+ row.officer+" "+row.keshi;
    },
    formatResult : function(row) {
     return row.cname;
    }
   }).result( function(event, row, formatted) {
    //alert(row.authorsid);//别alert() 死循环 再次给hidden赋值
   });
   }
  );
 }
}

说明:jquery autocomplete在我写完这json后,感觉不是很好用,反应比较慢,或许是因为嵌套在getJSON中

 

3 服务器端代码

public String findListAuthorByName() throws IOException{
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setContentType("application/json");
  response.setCharacterEncoding("UTF-8");
  response.setHeader("Cache-Control", "no-cache");
  PrintWriter pw= response.getWriter();
  if("".equals(authorName.trim()) || null==searchCon || !"authorName".equals(searchCon.trim())){//查询条件不是authorName,并且没有参数传递
   pw.print("");
   pw.flush();
   pw.close();
   return null;
  }

authorName=URLDecoder.decode(authorName,"utf-8");//这句如果你使用jquery autocomplete必须有,获取你改成其他的,这主要是处理jquery传递过来的中午是%456这种编码的,DIV就不用了


  List<Authors> lista = authorsService.findEntityListByLike("cname",authorName.trim());
  lista= lista.subList(0, (9 > lista.size()) ? lista.size() : 9);
  Dict dict=null;
  for(Authors authors : lista){
   String officer = authors.getOfficer();
   String keshi = authors.getKeshi();
   if(null!=officer && !"".equals(officer) ){
    dict = dictService.find(Integer.parseInt(officer));
    if(null!=dict){
     if("null".equalsIgnoreCase(dict.getDname())){
      authors.setOfficer("");
     }else{
      authors.setOfficer(dict.getDname());
     }
    }else{
     authors.setOfficer("");
    }
   }else{
    authors.setOfficer("");
   }
   if(null!=keshi && !"".equals(keshi) ){
    dict = dictService.find(Integer.parseInt(keshi));
    if(null!=dict){
     if("null".equalsIgnoreCase(dict.getDname())){
      authors.setKeshi("");
     }else{
      authors.setKeshi(dict.getDname());
     }
    }else{
     authors.setKeshi("");
    }
   }else{
    authors.setKeshi("");
   }
  }
  JSONArray jsonObject = JSONArray.fromObject(lista);
  String resultString = "";
  try {
   resultString = jsonObject.toString();
  } catch (Exception e) {
   resultString = "";
  }
  pw.print(resultString);
  pw.flush();
  pw.close();
  return null;
 }

 

 

还是在此说一些废话吧,搞开发的不管怎么样你都要会写JS,自己背不下来不要紧,重要的是你能够在任务时间内完成,至于在面试的时候遇到JS的题,这就得看你写过的了,记得那次面试的时候,那公司大部分是JS题,笔试后没想回去,呵呵,慢慢觉得敲代码也是需要你带感情的!