js实现百度搜索
使用JavaScript实现百度搜索功能
通过JavaScript可以实现调用百度搜索的功能,以下是几种常见的方法:
方法一:通过修改URL跳转实现
在HTML中创建一个输入框和按钮,通过JavaScript获取输入内容并跳转到百度搜索页面:
<input type="text" id="searchInput" placeholder="输入搜索内容">
<button onclick="baiduSearch()">百度搜索</button>
<script>
function baiduSearch() {
const query = document.getElementById('searchInput').value;
if(query.trim()) {
window.location.href = `https://www.baidu.com/s?wd=${encodeURIComponent(query)}`;
}
}
</script>
方法二:使用表单提交方式

通过HTML表单直接提交到百度搜索接口:
<form action="https://www.baidu.com/s" target="_blank">
<input type="text" name="wd" placeholder="输入搜索内容">
<button type="submit">百度搜索</button>
</form>
方法三:在新窗口打开搜索结果
修改第一个方法,实现在新窗口打开搜索结果:

function baiduSearch() {
const query = document.getElementById('searchInput').value;
if(query.trim()) {
window.open(`https://www.baidu.com/s?wd=${encodeURIComponent(query)}`, '_blank');
}
}
方法四:使用百度搜索API
百度提供了自定义搜索API,可以更灵活地集成搜索功能:
function customBaiduSearch(query) {
// 需要先在百度开发者平台申请API key
const apiKey = 'YOUR_API_KEY';
fetch(`https://www.baidu.com/s?wd=${encodeURIComponent(query)}&apiKey=${apiKey}`)
.then(response => response.json())
.then(data => {
// 处理返回的搜索结果
console.log(data);
});
}
注意事项
- 使用encodeURIComponent对搜索关键词进行编码,确保特殊字符正确处理
- 考虑添加输入验证,防止空搜索
- 如需商业使用,建议申请百度官方API
- 移动端适配时,可以考虑使用百度移动搜索接口
以上方法可以根据实际需求选择使用,最简单的方式是通过表单提交或URL跳转实现基本搜索功能。






