ajax - 模板引擎模仿百度搜索

image

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }
        input {
            border: 0;
            outline: none;
        }
        .box {
            width: 500px;
            height: 50px;
            margin: 20px auto;
        }
        .box .search-box {
            float: left;
            width: 400px;
            border: 2px solid #0af;
            box-sizing: border-box;
        }
        .box .search-box .txt {
            display: block;
            height: 46px;
            line-height: 46px;
            color: #333;
            font-size: 16px;
            padding-left: 10px;
        }
        .box .search-box ul li{
            padding: 0 10px;
            line-height: 36px;
        }
        .box .btn {
            float: left;
            width: 100px;
            height: 50px;
            background-color: #0af;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="search-box">
            <input type="text" class="txt">
            <ul class="suggest-list">
                
            </ul>
        </div>
        <input type="button" value="搜索" class="btn">
    </div>

    <script src="js/jquery-1.12.4.min.js"></script>
    <script src="js/template-native.js"></script>
    <script type="text/html" id="tem">
        <% for(var i =0;i<g.length;i++){ %>
            <li><%= g[i].q %></li>
        <%}%>
    
    </script>
    <script>
        //按键弹起事件
        var $txt = $(".txt");
        var $ul = $(".suggest-list");

        $txt.keyup(function(){
            //搜索联想的数据
            var keyword = $(this).val();

            $.ajax({
                url: "https://www.baidu.com/sugrec?pre=1&p=3&ie=utf- 8&json=1&prod=pc&from=pc_web",
                dataType: "jsonp",
                jsonp: "cb",
                data : {"wd": keyword},
                success: function(data){
                    console.log(data);
                    //直接调用模板, 添加给ul
                    $ul.html(template("tem",data));
                }

            })
        })
    </script>
</body>

</html>
posted @ 2021-08-26 19:46  charonmomo  阅读(36)  评论(0编辑  收藏  举报