iBase4j前端01_bootstrap-suggest json-server模拟后台数据bootstrap-suggest环境搭建开启bootstrap-suggest的post和put请(代

Posted 寻渝记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iBase4j前端01_bootstrap-suggest json-server模拟后台数据bootstrap-suggest环境搭建开启bootstrap-suggest的post和put请(代相关的知识,希望对你有一定的参考价值。

 

1 准备

  1.1 模拟的json数据

{
    "info": [
        {
        "message": "信息",
        "value": [
            {
                "userName": "淳芸",
                "shortAccount": "chunyun",
                "userId": 20001
            }, {
                "userName": "orion-01",
                "userName": "orion-01",
                "shortAccount": "orion-01",
                "userId": 20000
            }, {
                "userName": "唐宏禹14",
                "shortAccount": "TANGHONGYU",
                "userId": 20011
            }, {
                "userName": "唐宏禹13",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "穆晓晨",
                "shortAccount": "mUXIAOCHEN",
                "userId": 20002
            }, {
                "userName": "张欢引",
                "shortAccount": "zhanghuanyin",
                "userId": 20003
            }, {
                "userName": "吴琼",
                "shortAccount": "wuqiong",
                "userId": 20004
            }, {
                "userName": "吴东鹏",
                "shortAccount": "wudongpeng",
                "userId": 20005
            }, {
                "userName": "黄少铅",
                "shortAccount": "huangshaoqian",
                "userId": 20006
            }, {
                "userName": "胡运燕",
                "shortAccount": "yunyan",
                "userId": 20007
            }, {
                "userName": "刘幸",
                "shortAccount": "liuxing",
                "userId": 20008
            }, {
                "userName": "陈媛媛",
                "shortAccount": "CHENYUANYUAN",
                "userId": 20009
            }, {
                "userName": "李大鹏",
                "shortAccount": "dapeng",
                "userId": 20010
            }, {
                "userName": "唐宏禹",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "旷东林",
                "shortAccount": "kuangdonglin",
                "userId": 20010
            }, {
                "userName": "唐宏禹15",
                "shortAccount": "TANGhongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹12",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹11",
                "shortAccount": "TangHongYu",
                "userId": 20011
            }, {
                "userName": "旷东林",
                "shortAccount": "kuangdonglin",
                "userId": 20010
            }, {
                "userName": "唐宏禹10",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹9",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹8",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹7",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "旷东林",
                "shortAccount": "kuangdonglin",
                "userId": 20010
            }, {
                "userName": "唐宏禹6",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹5",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹4",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹3",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹2",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }, {
                "userName": "唐宏禹1",
                "shortAccount": "tanghongyu",
                "userId": 20011
            }
        ],
        "code": 200,
        "redirect": ""
    }]
}
data.json

  1.2 模拟后台服务

    利用json-server模拟后台,json-server使用详解

    进入到模拟数据所在文件夹,执行下面的语句

json-server 模拟数据文件 -p 启动端口

      例如:json-server data.json -p 8888

      启动效果如下:

    利用浏览器访问得到的响应如下:

 

2 下载相关依赖包

  2.1 jquery

    https://jquery.com/download/

 

  2.2 bootstrap

    https://v3.bootcss.com/

  2.3 bootstrap-suggest

    https://github.com/lzwme/bootstrap-suggest-plugin

 

3 编程步骤

  3.1 引入相关文件

    引入jquery、boostrap的css和js、引入bootstrap-suggest

  3.2 编写html代码

    技巧01:编写一个input和ul即可

    坑01:CSS类照着写,因为bootstrap-suggest依赖需要用到bootstrap相关的样式

  3.3 编写JS代码

  3.4 测试效果

  3.5 代码汇总

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Suggest使用案例</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">

<link rel="stylesheet" type="text/css" href="../css/common.css">

<!-- <link rel="stylesheet" type="text/css" href="../tool/bootstrap-3.3.7/dist/css/bootstrap-theme.min.css"> -->
<link rel="stylesheet" type="text/css" href="../tool/bootstrap-3.3.7/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../tool/bootstrap-3.3.7/dist/css/bootstrap.css">

<script type="text/javascript" src="../tool/jquery/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../tool/bootstrap-3.3.7/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../tool/bootstrap-suggest-plugin/dist/bootstrap-suggest.min.js"></script>

<script type="text/javascript" src="../js/demo01_suggest.js"></script>

</head>
<body>
    <div class="panel panel-primary">
        <div class="panel-heading">测试</div>
        <div class="panel-body">
            <div class="input-group">
                <input type="text" class="form-control" id="modalTest_input" autocomplete="off">
                <div class="input-group-btn">
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="">
                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-right" role="menu"></ul>
                </div>
            </div>
        </div>
        <div class="panel-footer">
            <span id="Timer"></span>
        </div>
    </div>
    <hr class="hr">

</body>
</html>
suggest.html
$().ready(function() {

    $("#modalTest_input").bsSuggest({
            url: " http://localhost:8888/info",
            allowNoKeyword: true,   // 是否允许非关键字搜索【默认true】
            showHeader: true, // 是否显示表头【默认true】
            clearable: true, // 是否开启清空数据【默认false】
            showBtn: true, // 是否显示下拉按钮【默认false】
            multiWord: true, //以分隔符号分割的多关键字支持 
            separator: ",", //多关键字支持时的分隔符 
            getDataMethod: \'url\', // 请求url
            effectiveFields: ["userName", "userId", "shortAccount"], // 显示的字段
            effectiveFieldsAlias:{userName: "姓名", userId: "用户ID", shortAccount: "账号"}, // 字段标题
            idField: "userId", // id字段
            keyField: "userName", // input元素中的显示字段
            fnPreprocessKeyword: function(keyword) { //请求数据前,对输入关键字作进一步处理方法。注意,应返回字符串
                // alert("搜索关键字:" + keyword);
                return keyword;
            },
            fnProcessData: function (result) {    // url 获取数据时,对数据的处理,作为 fnGetData 的回调函数
            var index, len, data = {value: []};
            var json = result[0];

            // 判断是否有响应数据
            if (!json || !json.value || json.value.length === 0) {
                console.log("没有数据");
                return false;
            }
            len = json.value.length;
            // 将获取到的数据放到data.value中
            for (index = 0; index < len; index++) {
                data.value.push(json.value[index]);
            }
            //字符串转化为 js 对象 【只要获取到数据】
            return data;
        }
        }).on(\'onDataRequestSuccess\', function (e, result) {
            console.log(\'onDataRequestSuccess: \', result);
        }).on(\'onSetSelectValue\', function (e, keyword, data) {
            console.log("选择一个过后:");
            console.log(\'onSetSelectValue: \', keyword, data);
        }).on(\'onUnsetSelectValue\', function () {
            console.log(\'onUnsetSelectValue\');
        }).on(\'onShowDropdown\', function (e, data) {
            console.log(\'onShowDropdown\', e.target.value, data);
        }).on(\'onHideDropdown\', function (e, data) {
            console.log(\'onHideDropdown\', e.target.value, data);
        });

    // 每间隔一秒刷新时间
    setInterval("gettime()", 1000);

    //获取时间并设置格式
    gettime = function GetTime() {
        var mon, day, now, hour, min, ampm, time, str, tz, end, beg, sec;
        /*
        mon = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
                "Sep", "Oct", "Nov", "Dec");
        */
        mon = new Array("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月",
                "九月", "十月", "十一月", "十二月");
        /*
        day = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
        */
        day = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
        now = new Date();
        hour = now.getHours();
        min = now.getMinutes();
        sec = now.getSeconds();
        if (hour < 10) {
            hour = "0" + hour;
        }
        if (min < 10) {
            min = "0" + min;
        }
        if (sec < 10) {
            sec = "0" + sec;
        }
        $("#Timer").html(
            now.getFullYear() + "年" + (now.getMonth() + 1) + "月" + now.getDate() + "日" + "  " + hour + ":" + min + ":" + sec
            );
    }
    
})
suggest.js

 

4 bootstrap-suggest进阶

  4.1 原有bug

    原来的bootstrap-suggest框架仅仅支持get请求

  4.2 需求

    需要进行put或者post请求,而且还需要向后台传值

  4.3 修改bootstrap-suggeest的源代码

    技巧01:bootstrap-suggest中有一个ajax方法,该方法接收两个参数

      参数一 -> options -> 就是我们在自定义js文件对bootstrap-suggest的一些配置信息

      参数二 -> keyword -> 就是input标签中输入的值

/**
 * Bootstrap Search Suggest
 * @desc    这是一个基于 bootstrap 按钮式下拉菜单组件的搜索建议插件,必须使用于按钮式下拉菜单组件上。
 * @author  renxia <lzwy0820#qq.com>
 * @github  https://github.com/lzwme/bootstrap-suggest-plugin.git
 * @since   2014-10-09
 *===============================================================================
 * (c) Copyright 2014-2016 http://lzw.me All Rights Reserved.
 ********************************************************************************/
(function (factory) {
    if (typeof define === "function" && define.amd) {
        define([\'jquery\'], factory);
    } else if (typeof exports === \'object\' && typeof module === \'object\') {
        factory(require(\'jquery\'));
    } else if (window.jQuery) {
        factory(window.jQuery);
    } else {
        throw new Error(\'Not found jQuery.\');
    }
})(function($) {
    var VERSION = \'VERSION_PLACEHOLDER\';
    var $window = $(window);
    var isIe = \'ActiveXObject\' in window; // 用于对 IE 的兼容判断
    var inputLock; // 用于中文输入法输入时锁定搜索

    // ie 下和 chrome 51 以上浏览器版本,出现滚动条时不计算 padding
    var chromeVer = navigator.userAgent.match(/Chrome\\/(\\d+)/);
    if (chromeVer) {
        chromeVer = +chromeVer[1];
    }
    var notNeedCalcPadding = isIe || chromeVer > 51;

    // 一些常量
    var BSSUGGEST = \'bsSuggest\';
    var onDataRequestSuccess = \'onDataRequestSuccess\';
    var DISABLED = \'disabled\';
    var TRUE = true;
    var FALSE = false;

    /**
     * 错误处理
     */
    function handleError(e1, e2) {
        if (!window.console || !window.console.trace) {
            return;
        }
        console.trace(e1);
        if (e2) {
            console.trace(e2);
        }
    }
    /**
     * 获取当前 tr 列的关键字数据
     */
    function getPointKeyword($list) {
        return $list.data();
    }
    /**
     * 设置或获取输入框的 alt 值
     */
    function setOrGetAlt($input, val) {
        return val !== undefined ? $input.attr(\'alt\', val) : $input.attr(\'alt\');
    }
    /**
     * 设置或获取输入框的 data-id 值
     */
    function setOrGetDataId($input, val) {
        return val !== (void 0) ? $input.attr(\'data-id\', val) : $input.attr(\'data-id\');
    }
    /**
     * 设置选中的值
     */
    function setValue($input, keywords, options) {
        if (!keywords || !keywords.key) {
            return;
        }

        var separator = options.separator || \',\',
            inputValList,
            inputIdList,
            dataId = setOrGetDataId($input);

        if (options && options.multiWord) {
            inputValList = $input.val().split(separator);
            inputValList[inputValList.length - 1] = keywords.key;

            //多关键字检索支持设置id --- 存在 bug,不建议使用
            if (!dataId) {
                inputIdList = [keywords.id];
            } else {
                inputIdList = dataId.split(separator);
                inputIdList.push(keywords.id);
            }

            setOrGetDataId($input, inputIdList.join(separator))
                .val(inputValList.join(separator))
                .focus();
        } else {
            setOrGetDataId($input, keywords.id || \'\').val(keywords.key).focus();
        }

        $input.data(\'pre-val\', $input.val())
            .trigger(\'onSetSelectValue\', [keywords, (options.data.value || options._lastData.value)[keywords.index]]);
    }
    /**
     * 调整选择菜单位置
     * @param {Object} $input
     * @param {Object} $dropdownMenu
     * @param {Object} options
     */
    function adjustDropMenuPos($input, $dropdownMenu, options) {
        if (!$dropdownMenu.is(\':visible\')) {
            return;
        }

        var $parent = $input.parent();
        var parentHeight = $parent.height();
        var parentWidth = $parent.width();

        if (options.autoDropup) {
            setTimeout(function() {
                var offsetTop = $input.offset().top;
                var winScrollTop = $window.scrollTop();
                var menuHeight = $dropdownMenu.height();

                if ( // 自动判断菜单向上展开
                    ($window.height() + winScrollTop - offsetTop) < menuHeight && // 假如向下会撑长页面
                    offsetTop > (menuHeight + winScrollTop) // 而且向上不会撑到顶部
                ) {
                    $parent.addClass(\'dropup\');
                } else {
                    $parent.removeClass(\'dropup\');
                }
            }, 10);
        }

        // 列表对齐方式
        var dmcss = {};
        if (options.listAlign === \'left\') {
            dmcss = {
                \'left\': $input.siblings(\'div\').width() - parentWidth,
                \'right\': \'auto\'
            };
        } else if (options.listAlign === \'right\') {
            dmcss = {
                \'left\': \'auto\',
                \'right\': 0
            };
        }

        // ie 下,不显示按钮时的 top/bottom
        if (isIe && !options.showBtn) {
            if (!$parent.hasClass(\'dropup\')) {
                dmcss.top = parentHeight;
                dmcss.bottom = \'auto\';
            } else {
                dmcss.top = \'auto\';
                dmcss.bottom = parentHeight;
            }
        }

        // 是否自动最小宽度
        if (!options.autoMinWidth) {
            dmcss.minWidth = parentWidth;
        }
        /* else {
            dmcss[\'width\'] = \'auto\';
        }*/

        $dropdownMenu.css(dmcss);

        return $input;
    }
    /**
     * 设置输入框背景色
     * 当设置了 indexId,而输入框的 data-id 为空时,输入框加载警告色
     */
    function setBackground($input, options) {
        var inputbg, bg, warnbg;
        if ((options.indexId === -1 && !options.idField) || options.multiWord) {
            return $input;
        }

        bg = options.inputBgColor;
        warnbg = options.inputWarnColor;

        var curVal = $input.val();
        var preVal = $input.data(\'pre-val\');

        if (setOrGetDataId($input) || !curVal) {
            $input.css(\'background\', bg || \'\');

            if (!curVal && preVal) {
                $input.trigger(\'onUnsetSelectValue\').data(\'pre-val\', \'\');
            }

            return $input;
        }

        inputbg = $input.css(\'backgroundColor\').replace(/ /g, \'\').split(\',\', 3).join(\',\');
        // 自由输入的内容,设置背景色
        if (!~warnbg.indexOf(inputbg)) {
            $input.trigger(\'onUnsetSelectValue\') // 触发取消data-id事件
                .data(\'pre-val\', \'\')
                .css(\'background\', warnbg);
        }

        return $input;
    }
    /**
     * 调整滑动条
     */
    function adjustScroll($input, $dropdownMenu, options) {
        // 控制滑动条
        var $hover = $input.parent().find(\'tbody tr.\' + options.listHoverCSS),
            pos, maxHeight;

        if ($hover.length) {
            pos = ($hover.index() + 3) * $hover.height();
            maxHeight = +$dropdownMenu.css(\'maxHeight\').replace(\'px\', \'\');

            if (pos > maxHeight || $dropdownMenu.scrollTop() > maxHeight) {
                pos = pos - maxHeight;
            } else {
                pos = 0;
            }

            $dropdownMenu.scrollTop(pos);
        }
    }
    /**
     * 解除所有列表 hover 样式
     */
    function unHoverAll($dropdownMenu, options) {
        $dropdownMenu.find(\'tr.\' + options.listHoverCSS).removeClass(options.listHoverCSS);
    }
    /**
     * 验证 $input 对象是否符合条件
     *   1. 必须为 bootstrap 下拉式菜单
     *   2. 必须未初始化过
     */
    function checkInput($input, $dropdownMenu, options) {
        if (
            !$dropdownMenu.length || // 过滤非 bootstrap 下拉式菜单对象
            $input.data(BSSUGGEST) // 是否已经初始化的检测
        ) {
            return FALSE;
        }

        $input.data(BSSUGGEST, {
            options: options
        });

        return TRUE;
    }
    /**
     * 数据格式检测
     * 检测 ajax 返回成功数据或 data 参数数据是否有效
     * data 格式:{"value": [{}, {}...]}
     */
    function checkData(data) {
        var isEmpty = TRUE, o;

        for (o in data) {
            if (o === \'value\') {
                isEmpty = FALSE;
                break;
            }
        }
        if (isEmpty) {
            handleError(\'返回数据格式错误!\');
            return FALSE;
        }
        if (!data.value.length) {
            // handleError(\'返回数据为空!\');
            return FALSE;
        }

        return data;
    }
    /**
     * 判断字段名是否在 options.effectiveFields 配置项中
     * @param  {String} field   要判断的字段名
     * @param  {Object} options
     * @return {Boolean}        effectiveFields 为空时始终返回 true
     */
    function inEffectiveFields(field, options) {
        var effectiveFields = options.effectiveFields;

        return !(field === \'__index\' ||
            effectiveFields.length &&
            !~$.inArray(field, effectiveFields));
    }
    /**
     * 判断字段名是否在 options.searchFields 搜索字段配置中
     */
    function inSearchFields(field, options) {
        return ~$.inArray(field, options.searchFields);
    }
    /**
     * 通过下拉菜单显示提示文案
     */
    function showTip(tip, $input, $dropdownMenu, options) {
        $dropdownMenu.html(\'<div style="padding:10px 5px 5px">\' + tip + \'</div>\').show();
        adjustDropMenuPos($input, $dropdownMenu, options);
    }
    /**
     * 下拉列表刷新
     * 作为 fnGetData 的 callback 函数调用
     */
    function refreshDropMenu($input, data, options) {
        var $dropdownMenu = $input.parent().find(\'ul:eq(0)\'),
            len, i, field, index = 0,
            tds,
            html = [\'<table class="table table-condensed table-sm" style="margin:0">\'],
            idValue, keyValue; // 作为输入框 data-id 和内容的字段值
        var dataList = data.value;

        if (!data || !dataList || !(len = dataList.length)) {
            if (options.emptyTip) {
                showTip(options.emptyTip, $input, $dropdownMenu, options);
            } else {
                $dropdownMenu.empty().hide();
            }
            return $input;
        }

        // 相同数据,不用继续渲染了
        if (
            options._lastData &&
            JSON.stringify(options._lastData) === JSON.stringify(data) &&
            $dropdownMenu.find(\'tr\').length === len
        ) {
            $dropdownMenu.show();
            return adjustDropMenuPos($input, $dropdownMenu, options);
            // return $input;
        }
        options._lastData = data;

        // 生成表头
        if (options.showHeader) {
            html.push(\'<thead><tr>\');
            for (field in dataList[0]) {
                if (!inEffectiveFields(field, options)) {
                    continue;
                }

                html.push(\'<th>\', (options.effectiveFieldsAlias[field] || field),
                    index === 0 ? (\'(\' + len + \')\') : \'\' , // 表头第一列记录总数
                    \'</th>\');

                index++;
            }
            html.push(\'</tr></thead>\');
        }
        html.push(\'<tbody>\');

        // console.log(data, len);
        // 按列加数据
        var dataI;
        for (i = 0; i < len; i++) {
            index = 0;
            tds = [];
            dataI = dataList[i];
            idValue = dataI[options.idField] || \'\';
            keyValue = dataI[options.keyField] || \'\';

            for (field in dataI) {
                // 标记作为 value 和 作为 id 的值
                if (!keyValue && options.indexKey === index) {
                    keyValue = dataI[field];
                }
                if (!idValue && options.indexId === index) {
                    idValue = dataI[field];
                }

                index++;

                // 列表中只显示有效的字段
                if (inEffectiveFields(field, options)) {
                    tds.push(\'<td data-name="\', field, \'">\', dataI[field], \'</td>\');
                }
            }

            html.push(\'<tr data-index="\', (dataI.__index || i),
                \'" data-id="\', idValue,
                \'" data-key="\', keyValue, \'">\',
                tds.join(\'\'), \'</tr>\');
        }
        html.push(\'</tbody></table>\');

        $dropdownMenu.html(html.join(\'\')).show();

        // scrollbar 存在时,延时到动画结束时调整 padding
        setTimeout(function() {
            if (notNeedCalcPadding) {
                return;
            }

            var $table = $dropdownMenu.find(\'table:eq(0)\'),
                pdr = 0,
                mgb = 0;

            if (
                $dropdownMenu.height() < $table.height() &&
                +$dropdownMenu.css(\'minWidth\').replace(\'px\', \'\') < $dropdownMenu.width()
            ) {
                pdr = 18;
                mgb = 20;
            }

            $dropdownMenu.css(\'paddingRight\', pdr);
            $table.css(\'marginBottom\', mgb);
        }, 301);

        adjustDropMenuPos($input, $dropdownMen

以上是关于iBase4j前端01_bootstrap-suggest json-server模拟后台数据bootstrap-suggest环境搭建开启bootstrap-suggest的post和put请(代的主要内容,如果未能解决你的问题,请参考以下文章

java开源架构推荐

前端期末考试试题及参考答案(01)

前端期末考试试题及参考答案(01)

总结2016年十大开源项目,看看你用到了没?

前端架构_从入门到微前端分享

从0到上线开发企业级电商项目_前端_01_sublime使用技巧