jsonp实现百度搜索提示

直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>搜索提示</title>
    <style>
        #q {
            width: 300px; 
            height: 30px; 
            padding: 5px; 
            border:1px solid rgb(68, 128, 233); 
            font-size: 16px;}
        #ul1 {
            border:1px solid rgb(68, 128, 233); 
            width: 310px; 
            margin: 0;
            padding: 0; 
            display: none;
            }
        li a { 
            line-height: 30px; 
            padding: 5px; 
            text-decoration: none; 
            color: black; 
            display: block;
            }
        li a:hover{ 
            background: rgb(68, 128, 233);; 
            color: white; 
            }
    </style>
</head>
<body>
    <input type="text" id="q" />
    <ul id="ul1"></ul>
    <script>
        var oQ = document.getElementById('q');
        var oUl = document.getElementById('ul1');
        function peri(data) {
            var html = '';
            if (data.s.length) {
                oUl.style.display = 'block';
                for (var i=0; i<data.s.length; i++) {
                    html += '<li><a target="_blank" href="http://www.baidu.com/s?wd='+data.s[i]+'">'+ data.s[i] +'</a></li>';
                }
                oUl.innerHTML = html;
            } else {
                oUl.style.display = 'none';
            }
        } 
        oQ.onkeyup = function() {
            if(this.value != '') {
                var oScript = document.createElement('script');
                oScript.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=peri';
                document.body.appendChild(oScript);
            }else {
                oUl.style.display = 'none';
            }
        }
    </script>
</body>
</html>

获取接口地址:控制台--copy link adress --查看返回信息

jsop的原理与实现:利用script标签的异步加载实现。

总结jsonp大致步骤

1.给服务端传递回调名

2.以这个函数名注册一个全局的函数

3.动态创建一个script标签

4.监听脚本的响应事件

5.最后删除函数和变量

原文地址:https://www.cnblogs.com/PeriHe/p/8565614.html