<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
li{
cursor: pointer;
}
</style>
</head>
<body>
<input type="text" id="search">
<button id="go">走</button>
<ul id="box">
</ul>
<script src="./JSONP.js"></script>
<script>
// 1获取元素
let search = document.getElementById('search')
let box = document.getElementById('box')
let url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su"
let go = document.getElementById('go')
// 2键盘抬起事件
search.onkeyup = throttle(function(){
// 3jsonp请求
// 如果内容为空删除
if(search.value.trim()==""){
return box.remove()
}
// 删除ul,创建一个ul方便渲染数据
box.remove()
let ul = document.createElement('ul')
ul.id = "box"
document.body.appendChild(ul)
box = document.getElementById('box')
// 事件委托 移入li的事件
document.onmouseover = function(e){
e = e || window.event
e.preventDefault()
if(e.target.nodeName == "LI"){
for(let li of box.children){
li.style.backgroundColor = "#fff"
li.onclick =function(){
search.value = li.innerText
}
}
e.target.style.backgroundColor = 'red'
console.log(e.target)
}else{
// console.log("111")
for(let li of box.children){
li.style.backgroundColor = '#fff'
}
}
}
jsonp({
url,
params:{
wd:search.value
},
callbackName:'cb',
callback(res){
// 获取数据判断是否为空
if(res.s.length != 0){
// 文档碎片 节性能
let frg = document.createDocumentFragment()
for(let v of res.s){
let li = document.createElement('li')
li.innerText = v
// li.style = "cursor: pointer;"
// li.onclick = function(e){
// e = e || window.event
// e.preventDefault()
// search.value = v
// box.remove()
// }
frg.appendChild(li)
}
box.appendChild(frg)
}
}
})
},200)
// go添加点击事件
go.addEventListener("click",function(){
jsonp({
url,
params:{
wd:search.value
},
callbackName:'cb',
callback(res){
window.location.href = `https://www.baidu.com/s?wd=${search.value}`
}
})
})
// 节流
function throttle(func,wait){
let flag = false
return function(){
if(flag) return
flag = true
let timer = setTimeout(()=>{
func()
flag = false
},wait)
}
}
</script>
</body>
</html>
function jsonp(object){
// {链接地址,参数(对象),回调函数名字,回调函数}
let {url,params,callbackName,callback} = object
// 给window添加方法
// 随机生成一个函数名 不能重复
let fnName = "fn" + Date.now() + Math.ceil(Math.random()*10000)
// 将对应回调函数添加給window 添加的函数名随机
window[fnName] = callback
// 创建标签script
let script = document.createElement("script")
// 将方法名拼接到url地址后面 跨域执行xxx
url += `?${callbackName}=${fnName}`
// 将参数拼接
url += joinParams(params)
// 将这个url地址给到script标签的src属性(自带的属性)
script.src = url
// 将script加到body
document.body.appendChild(script)
// 判断是否已经加载成功,加载成功后就删除script节约空间
script.onload = function(){
script.remove()
delete window[fnName]
}
}
function joinParams(params){
let str = ''
// 取出对象的值
for(let key in params){
str+=`&${key}=${params[key]}`
}
return str
}
跨域请求,百度搜索