当前位置:编程学习 > JAVA >>

jquery autocomplete插件结合ajax使用demo

首先是引入文件,除了juqery和juqeryUI的基本文件外,还需要引入下面的文件
1 <!-- autocomplete -->
2 <script src="<%=request.getContextPath()%>/share/js/jqueryPlugin/autoComplete/jquery.ui.core.js"></script>
3 <script src="<%=request.getContextPath()%>/share/js/jqueryPlugin/autoComplete/jquery.ui.widget.js"></script>
4 <script src="<%=request.getContextPath()%>/share/js/jqueryPlugin/autoComplete/jquery.ui.position.js"></script>
5 <script src="<%=request.getContextPath()%>/share/js/jqueryPlugin/autoComplete/jquery.ui.autocomplete.js"></script>
接下来就是使用,js文件如下:
01 $( "#tags" ).autocomplete({
02             source: function( request, response ) {
03                 $.ajax({
04                     url: "sql/sqlgetWebsqlDataBaseInforAjax",
05                     dataType: "json",
06                     data:{
07                         searchDbInforItem: request.term
08                     },
09                     success: function( data ) {
10                         response( $.map( data, function( item ) {
11                             return {
12                                 dbId:item.dbid,
13                                 jdbcUrl:item.jdbcUrl,
14                                 ip:item.ip,
15                                 port:item.port,
16                                 sch:item.sch,
17                                 username: item.username,
18                                 password:item.password,
19                                 value: item.labelview
20                             }
21                         }));
22                     }
23                 });
24             },
25             minLength: 1,
26             select: function( event, ui ) {
27                 $("#dbInforDdId").val(ui.item.dbId);
28                 $("#dbInforDdjdbcUrl").val(ui.item.jdbcUrl);
29                 $("#dbInforIp").val(ui.item.ip);
30                 $("#dbInforPort").val(ui.item.port);
31                 $("#dbInforSch").val(ui.item.sch);
32                 $("#dbInforUserName").val(ui.item.username);
33                 $("#dbInforPassword").val(ui.item.password);
34             }
35         });
这段脚本是给tag这个input加入autocomplete插件,然后通过request.term取到模糊搜索的词,然后调用ajax返回一个json串到response中,其中用到了一个map函数。然后实现select方法,即把response的item通过ui.item写入到各个input中。实现数据自动填充。
其中,有个label和value参数,lable是下拉框中显示的值,value是选中后自动填充的值,可以分别设置,也可以只设置一个,例如我就只设置一个value。
效果如下:
 


 
接下来,对这个脚本加以改进,加入cache,这样就不用每次都通过ajax来获取。改进的脚本如下:
 
 
01 //autocomplete插件
02         //缓存
03         var cache = {};
04         $( "#tags" ).autocomplete({
05             source: function(request, response ) {
06                 var term = request.term;
07                 if ( term in cache ) {
08                     response( $.map( cache[ term ], function( item ) {
09                         return {
10                             db

补充:web前端 , JavaScript ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,