您的位置:首页 > Web前端 > JavaScript

原生JavaScript代码实现 jsonp 跨域请求

2018-03-06 14:42 363 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/monoplasty/article/details/79458127

jsonp简单实现百度搜索功能代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{padding: 0;margin: 0;}
#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>
<script>
// 名字自定义的回调函数 处理获取到的数据
function callback(data) {
var show = document.getElementById('show');
var html = "";
if(data.s.length) {
show.style.display = 'block';
var len = data.s.length;
for (var i=0; i<len; i++) {
html += '<li><a target="_blank" href="http://www.baidu.com/s?wd='+data.s[i]+'">'+ data.s[i] +'</a></li>';
}
show.innerHTML = html;
}else{
show.style.display = "none";
}
}

window.onload = function(){
var oQ = document.getElementById('q'),
show = document.getElementById('show');

oQ.onkeyup = function(){
if(this.value!=""){
var oScript = document.createElement("script");
// callback 为自定义的函数名字
oScript.src = 'http://suggestion.baidu.com/su?wd='+this.value+'&cb=callback';
document.body.appendChild(oScript);
} else{
show.style.display = "none";
}
}
}
</script>
</head>
<body>
<input type="text" id="q">
<ul id="show"></ul>
</body>
</html>
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: