Ajax跨域实现淘宝/百度搜索下拉提示效果

最近学到Ajax,觉得自己对与前后端的数据交互有了一个基本的了解。下面是Ajax应用到淘宝/百度的搜索功能的一个简单的小实例,就是输入一个词,下拉框中自动显示匹配的内容:

页面的布局比较简单,就是一个input输入框和一个下拉的ul列表:

<body>
    <input type="text" id="q" />
    <ul id="ul1"></ul>
</body>

给两个框加上简单的样式,ul的display:none;后续在js里面创建元素:

<style>
#q {width: 300px; height: 30px; padding: 5px; border:1px solid #f90; font-size: 16px;}
#ul1 {border:1px solid #f90; 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: #f90; color: white; }
</style>

js中用到Ajax跨域解决方案JSONP:在页面创建一个script标签,设置src属性,加入参数,用函数angel(data)处理获取过来的数据,将数据加入到ul列表中,点击下拉列表中的数据跳转到百度搜索页面:

<script>
function angel(data) {
    
    var oUl = document.getElementById('ul1');
    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';
    }
    
}
window.onload = function() {
    
    var oQ = document.getElementById('q');
    var oUl = document.getElementById('ul1');
    
    oQ.onkeyup = function() {
        
        if ( this.value != '' ) {
            var oScript = document.createElement('script');
            oScript.src = 'http://suggestion.baidu.com/su?wd='+this.value+'&cb=angel';
            document.body.appendChild(oScript);
        } else {
            oUl.style.display = 'none';
        }    
    }
}
</script>

 

posted @ 2016-11-29 11:10  雨水一盒~  阅读(345)  评论(0编辑  收藏  举报