js实现百度搜索
使用JavaScript实现百度搜索功能
通过JavaScript可以实现在网页中调用百度搜索的功能。以下是几种常见的实现方式:
通过表单提交实现
创建一个HTML表单,设置action为百度搜索URL,method为GET:
<form action="https://www.baidu.com/s" method="get" target="_blank">
<input type="text" name="wd" placeholder="输入搜索内容">
<button type="submit">百度搜索</button>
</form>
通过JavaScript跳转实现
使用window.location或window.open方法实现跳转到百度搜索页面:
function baiduSearch(keyword) {
const encodedKeyword = encodeURIComponent(keyword);
window.open(`https://www.baidu.com/s?wd=${encodedKeyword}`);
}
通过AJAX实现搜索建议
获取百度搜索建议的API(注意跨域问题需要后端代理):
function getSearchSuggestions(keyword) {
fetch(`https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&wd=${encodeURIComponent(keyword)}`)
.then(response => response.json())
.then(data => {
console.log(data.g); // 搜索建议数据
});
}
使用百度搜索API
百度官方提供了搜索API,需要申请API key:
const BAIDU_API_KEY = 'your_api_key';
function searchWithBaiduAPI(query) {
const url = `https://www.baidu.com/api?key=${BAIDU_API_KEY}&q=${encodeURIComponent(query)}`;
fetch(url)
.then(response => response.json())
.then(data => {
// 处理搜索结果
});
}
注意事项
- 直接调用百度搜索接口可能会遇到跨域问题,建议通过后端服务代理请求
- 百度搜索API有使用限制,需要遵守百度的开发者协议
- 对用户输入的关键词需要进行URL编码,使用encodeURIComponent函数
- 商业项目中使用百度搜索功能可能需要获得授权







