jquery ajax 实现百度搜索跨域

https://sp0.baidu.com/5a1Fazu…
百度搜索q返回的搜索结果
demo({q:”q”,p:false,s:[“qq邮箱”,”qq”,”汽车之家”,”全民tv”,”qq空间”,”qq下载”,”驱动精灵”,”去哪儿网”,”qq音乐”,”千图网”]});

<!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>
    原文作者:sgosky
    原文地址: https://segmentfault.com/a/1190000008629517
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞