标签:his ext i++ append ISE reject body select 百度搜
主要借助百度搜索的API,调用时会存在跨域问题,需要通过JSONP来解决这个问题,代码如下(代码中部分使用ES6语法):
HTML
<input type="text" id="input"> <div id="text"></div>
js:
document.querySelector(‘#input‘).oninput = function () { let val = this.value; jsonp({ url: ‘https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su‘, params: {wd: val}, cb: ‘show‘ }).then(res => { // console.log(res); let str = ‘<ul>‘; for (let i = 0, length = res.s.length; i < length; i++) { str += `<li>${res.s[i]}</li>` } str += ‘</ul>‘ document.querySelector(‘#text‘).innerHTML = str; }, err => { console.log(err) }) } function jsonp({url,params,cb}) { return new Promise((resolve, reject) => { window[cb] = function (data) { resolve(data); } params = { ...params,cb}; let arr = []; for (let key in params) { arr.push(`${key}=${params[key]}`) } let script = document.createElement(‘script‘) script.src = `${url}?${arr.join("&")}` document.body.appendChild(script) }) }
标签:his ext i++ append ISE reject body select 百度搜
原文地址:https://www.cnblogs.com/web-wjg/p/9269681.html