Ajax异步加载数据获取baidu接口代码示例

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>JSONP百度搜索</title>
    <style>
        #q{
            width: 500px;
            height: 30px;
            border:1px solid #ddd;
            line-height: 30px;
            display: block;
            margin: 0 auto;
            padding: 0 10px;
            font-size: 14px;
        }
        #ul{
            width: 520px;
            list-style: none;
            margin: 0 auto;
            padding: 0;
            border:1px solid #ddd;
            margin-top: -1px;
            display: none;
        }
        #ul li{
            line-height: 30px;
            padding: 0 10px;
        }
        #ul li:hover{
            background-color: #f60;
            color: #fff;
        }
    </style>
    <script>
        // 2.步骤二
        // 定义demo函数 (分析接口、数据)
        function demo(data){
            var Ul = document.getElementById('ul');
            var html = '';
// 如果搜索数据存在 把内容添加进去
            if (data.s.length) {
// 隐藏掉的ul显示出来
                Ul.style.display = 'block';
// 搜索到的数据循环追加到li里
                for(var i = 0;i<data.s.length;i++){
                    html += '<li>'+data.s[i]+'</li>';
                }
// 循环的li写入ul
                Ul.innerHTML = html;
            }
        }
        // 1.步骤一
        window.onload = function(){
// 获取输入框和ul
            var Q = document.getElementById('q');
            var Ul = document.getElementById('ul');
// 事件鼠标抬起时候
            Q.onkeyup = function(){
// 如果输入框不等于空
                if (this.value != '') {
// ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆JSONPz重点
                ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
// 创建标签
                    var script = document.createElement('script');
//给定要跨域的地址 赋值给src
//这里是要请求的跨域的地址 我写的是百度搜索的跨域地址
                    script.src =
                        'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?
                    wd='+this.value+'&cb=demo';
// 将组合好的带src的script标签追加到body里
                    document.body.appendChild(script);
                }
            }
        }
    </script>
</head>
<body>
<input type="text" id="q" />
<ul id="ul">
</ul>
</body>
</html>

 

 
 
posted @ 2022-02-25 23:43  临易  阅读(96)  评论(0编辑  收藏  举报