跨域代码示例——模拟百度搜索

<!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: 150px;
            margin: 20px auto;
        }
        .box .search-box{
            float: left;
            width: 400px;
            box-sizing: border-box;
            border:2px solid cornflowerblue;       
        }
        .box .search-box .txt{
            display: block;
            height: 46px;
            line-height: 46px;
            color: #333;
            padding-left: 10px;
            font-size: 16px;

        }
        .box .search-box ul li{
            padding-left: 10px;
            line-height: 36px;
            color: #333;
        }
        .box .btn{
            float: left;
            width: 100px;
            height: 50px;
            background-color: cornflowerblue;
            font-size: 18px;
            color: #fff;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="search-box">
            <input type="text" class="txt">
            <ul class="suggest-list">
                <!-- <li>1</li>
                <li>2</li>
                <li>3</li> 
                <li>4</li> -->
            </ul>
        </div>
        <input type="button" value="搜索" class="btn">
    </div>

    <script src="jquery-1.12.4.min.js"></script>
    <script>
        //添加txt按键弹起事件,每输入一个文字都会触发事件
        var $txt = $(".txt");
        var $ul = $(".suggest-list");
        
        $txt.keydown(function(){
            //获取input内输入的内容
            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",
                // type:"get",
                dataType: "jsonp",
                jsonp: "cb",
                data: { "wd": keyword },
                success:function(data){
                    // console.log(data.g);
                    //获取需要的数据
                    var arr = data.g;
                    //将所有数组中的数据,渲染到页面中的ul里面
                    var str = "";
                    for(var i = 0;i < arr.length;i ++){
                        // 遍历数组,进行字符串拼接
                        // 字面量的方式 拼接字符串
                        str += `<li>${arr[i].q}</li>`;
                    }
                    //将最终拼接的字符串添加到页面上
                    $ul.html(str);
                }

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


posted @ 2021-05-04 11:40  小白可别不举铁  阅读(143)  评论(0编辑  收藏  举报