js 实现百度搜索
使用 JavaScript 实现百度搜索功能
在 JavaScript 中实现百度搜索功能,可以通过以下方法完成:
直接跳转百度搜索页面
通过构建百度搜索的 URL,将用户输入的搜索词传递给百度:
function searchBaidu(keyword) {
const encodedKeyword = encodeURIComponent(keyword);
window.location.href = `https://www.baidu.com/s?wd=${encodedKeyword}`;
}
// 调用示例
searchBaidu("JavaScript教程");
使用表单提交方式
创建一个表单,将搜索词提交到百度搜索页面:
<form id="baiduSearchForm" action="https://www.baidu.com/s" method="get" target="_blank">
<input type="text" name="wd" id="searchInput" placeholder="输入搜索内容">
<button type="submit">百度搜索</button>
</form>
使用 Fetch API 获取搜索结果(需要后端代理)
由于跨域限制,前端无法直接获取百度搜索结果。可以设置一个后端代理:
async function fetchBaiduResults(keyword) {
try {
const response = await fetch(`/api/baidu-proxy?q=${encodeURIComponent(keyword)}`);
const data = await response.json();
console.log(data);
// 处理返回的搜索结果
} catch (error) {
console.error('搜索出错:', error);
}
}
使用百度开放平台API(推荐)
百度提供了搜索API,需要申请API密钥:

const BAIDU_API_KEY = '你的API密钥';
async function searchWithBaiduAPI(keyword) {
const url = `https://api.baidu.com/search?q=${encodeURIComponent(keyword)}&ak=${BAIDU_API_KEY}`;
try {
const response = await fetch(url);
const results = await response.json();
// 处理返回的搜索结果
displayResults(results);
} catch (error) {
console.error('API请求失败:', error);
}
}
function displayResults(results) {
// 实现结果展示逻辑
console.log(results);
}
注意事项
- 直接跳转方法最简单,但无法自定义结果展示
- 表单提交方式会打开新页面
- 需要后端代理才能绕过跨域限制
- 百度官方API需要注册开发者账号并获取密钥
- 确保遵守百度的API使用条款和限制
以上方法可以根据具体需求选择适合的实现方式。对于简单的需求,直接跳转或表单提交即可;如需更复杂的集成,建议使用百度官方API。






