借助百度简单实现搜索功能
<!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>
<script src="../jquery-3.4.1.min.js"></script>
</head>
<body>
<input type="text">
<ul></ul>
<script>
$(function () {
$('input').keyup(function () {
var txt = $('input').val()
console.log(txt)
$.ajax({
url: 'https://www.baidu.com/sugrec?prod=pc&wd=' + txt,
method: 'get',
dataType: 'jsonp',
success: function (res) {
console.log(res)
console.log(res.g)
var data = res.g
var str = ''
data.forEach(function (value, index) {
if (index < 5) {
str += '<li>' + value['q'] + '</li>'
}
});
console.log(str)
$('ul').html(str)
},
error: function (err) {
console.log(err)
},
complete: function () {
}
})
})
})
</script>
</body>
</html>
跨域
<!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>
<script src="../jquery-3.4.1.min.js"></script>
</head>
<body>
<script>
// var script = document.createElement('script')
// script.src = 'https://www.baidu.com/sugrec?prod=pc&wd=qq&callback=showData'
// document.body.appendChild(script)
function showData(res){
console.log(res)
console.log(res.g)
}
$('body').append('<script src="https://www.baidu.com/sugrec?prod=pc&wd=qq&callback=showData"><\/script>')
</script>
</body>
</html>