jquery+ajax+autocomplete自动补全

需求:

根据用户输入关键字匹配接口,模糊查询并选中填充

实现:

用到插件:jquery的autoplete插件

代码:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>jQuery Ajax Autocomplete</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>

<body>
    <td>药店名称:
        <input type="text" name="phName" value="" id="phName" class="rph">
        <input type="hidden" name="rpId" id="rpId" />
    </td>
    <script>

        $(".rph").autocomplete({
            minLength: 1,
            source: function (request, response) {
         //特别注意:
         //source此方法返回数据为源数据,所以data.json数据必须处理
var info = request.term; var arr = []; $.ajax({ url: "data.json", type: "get", dataType: "json", success: function (data) { var len = data.length; var reg = new RegExp(info); for (var i = 0; i < len; i++) { if (data[i].deptName.match(reg)) { arr.push(data[i]); } } response($.map(arr, function (item) { return { label: item.deptName } })); } }); }, focus: function (event, ui) { $(".rph").val(ui.item.label); $("#rpId").val(ui.item.value); return false; }, select: function (event, ui) { $(".rph").val(ui.item.label); $("#rpId").val(ui.item.value); return false; } }); </script> </body> </html>

以下是data.json源数据:

[
    {
        "deptName": "感冒灵"
    },
    {
        "deptName": "小柴胡"
    },
    {
        "deptName": "板蓝根"
    },
    {
        "deptName": "连花清瘟"
    },
    {
        "deptName": "康泰"
    }
]

 

posted @ 2020-05-07 15:13  宫圆薰  阅读(535)  评论(0编辑  收藏  举报