利用跨域实现的模拟百度搜索提示的案例,关于这个案例在这里就不多说什么,我们直接上代码吧,关于跨域问题,感兴趣的小伙伴可以看一下我之前写的一篇:两种跨域方式:CORS--JSONP
<style>
* {
margin: 0px;
padding: 0
}
input {
width: 300px;
height: 30px;
border: 1px solid lightgray;
margin-top: 150px;
margin-left: 200px;
padding-left: 5px
}
ul {
width: 307px;
list-style: none;
margin-left: 200px;
display: none;
}
li {
height: 30px;
line-height: 30px;
border: 1px solid lightgray;
padding-left: 5px
}
</style>
<script>
function callbackDemo(response) {
var oUl = document.getElementById('ulList');
var html = '';
if (response.s.length != 0) {
oUl.style.display = 'block';
//循环遍历,将响应回来的数据放入响应的元素标签里
for (var i = 0; i < response.s.length; i++) {
html += '<li>' + response.s[i] + '</li>';
}
}
oUl.innerHTML = html;
}
window.onload = function() {
var oData = document.getElementById('inputSerach');
var oUl = document.getElementById('ulList');
oData.onkeyup = function() {
//判断输入框里是否有值
if (oData.value != '') {
var script = document.createElement('script');
//将路径放入script标签里
script.src = 'http://suggestion.baidu.com/su?wd=' + this.value + '&cb=callbackDemo';
document.body.appendChild(script);
} else {
oUl.style.display = 'none';
}
}
}
</script>
<input type="text" id="inputSerach" />
<ul id="ulList">
<li>123</li>
</ul>