先观察
对接口进行提炼:https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=关键词&cb=回调函数
简单测试一下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta
http-equiv="X-UA-Compatible" content="IE=edge"> <title>百度候选词</title> <meta
name="viewport" content="width=device-width, initial-scale=1"> <script> let
test = (data) => { console.log(data); } </script> <script
src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=dn&cb=test"></script>
</head> <body> <!--
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=关键词&cb=回调函数 --> </body>
</html>
效果:
尝试把内容放入一个ul内:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>百度候选词</title>
</head> <body> <ul id="myul"></ul> <script> //
为什么放ul的下面,可以看这篇文章:https://www.cnblogs.com/dotnetcrazy/p/10106976.html let test
= (json) => { let ulobj = document.getElementById("myul"); json.s.forEach(item
=> { let liobj = document.createElement("li"); liobj.innerHTML = item;
ulobj.appendChild(liobj); }); } //
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=关键词&cb=回调函数 </script>
<script
src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=dn&cb=test"></script>
</body> </html>
效果:
根据input输入动态获取
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>百度候选词</title>
<script> // https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=关键词&cb=回调函数
let show_ul = (json) => { let ul_obj = document.getElementById("myul");
ul_obj.innerHTML = ""; // 清空现在的ul console.log(json.s); json.s.forEach(item => {
let li_obj = document.createElement("li"); li_obj.innerHTML = item;
ul_obj.appendChild(li_obj); }); } window.onload = () => { let input_obj =
document.getElementById("myinput"); input_obj.oninput = () => { //
用script加载的方式,只会执行一次,不满足我们的需求,so ==> 动态创建 let script_obj =
document.createElement("script"); script_obj.src =
`https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${encodeURIComponent(input_obj.value)}&cb=show_ul`
document.body.appendChild(script_obj); //添加到body里面 } } </script> </head> <body>
<input type="text" id="myinput" /> <ul id="myul"></ul> </body> </html>
效果:
线上测试
可行,下面就美化,然后放入自己项目的input中了
热门工具 换一换