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>Document</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="box">
<form id="form" action="" class="form-inline" target="_blank">
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="search" autocomplete="off">
</div>
<button type="submit" class="btn btn-default" id="btn">search</button>
</form>
<ul class="list-group" id="list" style="width: 260px;">
</ul>
</div>
<script>
function loadScript(url) {
loadScript.mark = 'load';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.body.appendChild(script);
}
function callback(data) {
if (data) {
var arr = data.s;
var html = '';
for (var i = 0; i < arr.length; i++) {
html += "<li class='list-group-item'><a href='https://www.baidu.com/s?wd=" + arr[i] + "' target='_blank'>" + arr[i] + "</a></li>";
}
list.innerHTML = html;
}
}
search.onkeyup = function(e) {
e = e || event;
e.preventDefault();
console.log(e);
if (e.keyCode == '13') {
window.open('https://www.baidu.com/s?wd=' + this.value);
}
if (this.value) {
console.log(search.data);
if (search.data != this.value) {
form.setAttribute('action', 'https://www.baidu.com/s?wd=' + this.value);
var that = this;
loadScript('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + that.value + '&cb=callback')
}
} else {
list.innerHTML = '';
}
search.data = this.value;
}
search.onclick = function(e) {
e = e || event;
list.style.display = 'block';
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
document.onclick = function() {
list.style.display = 'none';
}
</script>
</body>
</html>
当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »