bootstrap-typeahead结合ajax动态提示

版权声明:本文为博主原创文章,未经博主允许不得转载


小旭今天想尝试下bootstrap-typeahead来做一个动态的输入框提示,于是乎踏上了几小时的研究之路。

在这里给大家分享下做法与经验吧。

首先,先奉上官网http://www.bootcdn.cn/bootstrap-3-typeahead/;

效果图:


这里我用bootstrap做前端,用struts2接后台json。当然咯,要是你用其他的也是没问题只要能正常传数据就行。


后台代码:

pom.xml:

<dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-json-plugin</artifactId>
  <version>${struts-version}</version>
</dependency>
<dependency>
  <groupId>net.sf.json-lib</groupId>
  <artifactId>json-lib</artifactId>
  <version>2.4</version>
  <classifier>jdk15</classifier>
</dependency>

struts.xml:

<package name="security" namespace="/security" extends="basepkg,json-default">
    <action name="*" class="securityAction" method="{1}">
        <result name="input">/jsps/login.jsp</result>
        <result name="main">/jsps/main.jsp</result>
        <result name="success" type="json">
            <param name="root">json</param>
        </result>
        <interceptor-ref name="guest" />
    </action>
</package>
Action:

private String json;
private Logger logger = Logger.getLogger(SecurityAction.class);
public String loadUserList() throws Exception{
    logger.info("服务器已经接收!"+user);
    List<User> userList =  userService.loadUserList(user);
    logger.info("查询到的记录条数!"+userList);
    Map<String, String> map = new HashMap<String, String>();
    for(User user:userList){
        map.put(user.getId(), user.getName());
    }
    JSONObject jo = JSONObject.fromObject(map);
    json = jo.toString();
    logger.debug(json);
    return SUCCESS;
}

Dao:

public List<User> loadUserList(String name) {
    List userList = getSession().createQuery("from User u where u.name like '%"+name+"%'").list();
    return userList;
}

前端代码:

我们需要2个js

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/2/6
  Time: 18:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/jsps/commons/taglib.jsp" %>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Form validation</title>
    <!-- Mobile specific metas -->
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <!-- Force IE9 to render in normal mode -->
    <!--[if IE]><meta http-equiv="x-ua-compatible" content="IE=9" /><![endif]-->
    <meta name="author" content="SuggeElson" />
    <meta name="description" content=""
    />
    <meta name="keywords" content=""
    />
    <meta name="application-name" content="sprFlat admin template" />

    <link href="<%=request.getContextPath()%>/assets/css/bootstrap.css" rel="stylesheet" />

    <meta name="msapplication-TileColor" content="#3399cc" />
</head>
<body>
<div class="well">
    <s:textfield id="search" name="sale.distributedUser.name"
                 cssClass="form-control"
                 autocomplete = "off"
                 data-provide = "typeahead"
                 type="text"
                 />
</div>
<script src="<%=request.getContextPath()%>/assets/js/jquery-1.8.3.min.js"></script>
<script src="<%=request.getContextPath()%>/js/framework/bootstrap-typeahead.js"></script>
<script>
    $(function () {
        $('.typeahead').typeahead();
        $('.typeahead').typeahead('destroy');
        var search =$("#search");
        $.get('<s:url namespace="/security" action="loadUserList" />',{'user.name':search.val()}, function(data){
            if(data){
                var strData = data.split("\"");
                for(index in strData){
                    if(strData[index].indexOf("{") != -1||strData[index].indexOf(",")!= -1||strData[index].indexOf("}")!= -1||strData[index].indexOf(":") != -1){
                        strData.splice(index, 1);
                    }
                }
                var arrId = new Array();//存放key的数组,Id也传过来是以防有名字一样的人。做唯一识别
                var arrName = new Array();//存放value的数组,用于显示
                for(index in strData){
                    if(index%2==0){
                        arrId.push(strData[index]);
                    }else{
                        arrName.push(strData[index]);
                    }
                }
                $("#search").typeahead({source: arrName,items:5});
            }
        },'json');
    })
</script>
</body>
</html>

其中

$("#search").typeahead({source: arrName});

这里面除了source还可以写其他参数:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值