如何在网页中使用新版Bing自定义搜索API?求更新后的JS代码
新版Bing Custom Search API网页JavaScript实现代码
微软已弃用旧版https://ui.customsearch.ai/api/ux/rendering-js嵌入脚本,目前有两种主流实现方式适配新版API:
方式一:使用官方嵌入式搜索组件(快速集成)
这种方式直接复用官方搜索UI组件,无需手动处理请求逻辑,只需替换你的Custom Config ID和API密钥:
<h2>Search Page</h2> <!-- 配置自定义搜索参数 --> <script type="text/javascript"> var customSearchOptions = { customConfig: "YOUR_CUSTOM_CONFIG_ID", // 替换为你的Custom Config ID apiKey: "YOUR_AZURE_API_KEY", // 替换为你的Azure API密钥 market: "en-US", // 根据需求修改市场区域 container: "bcs-search-container" }; </script> <!-- 加载新版自定义搜索UX组件 --> <script src="https://ui.customsearch.ai/api/ux/customsearch/script"></script> <!-- 搜索组件容器 --> <div id="bcs-search-container"></div>
方式二:手动调用REST API(自定义UI)
如果需要完全自定义搜索界面,可直接调用Bing Custom Search的REST API,以下是完整示例:
<h2>Search Page</h2> <!-- 自定义搜索UI --> <div class="search-container"> <input id="search-input" type="text" placeholder="Enter search term"> <button id="search-btn">Search</button> <div id="search-results"></div> </div> <script> // 配置核心参数 const API_KEY = "YOUR_AZURE_API_KEY"; // 替换为你的Azure API密钥 const CUSTOM_CONFIG_ID = "YOUR_CUSTOM_CONFIG_ID"; // 替换为你的Custom Config ID const MARKET = "en-US"; // 绑定搜索事件 document.getElementById('search-btn').addEventListener('click', performSearch); document.getElementById('search-input').addEventListener('keypress', e => { if (e.key === 'Enter') performSearch(); }); // 执行搜索逻辑 async function performSearch() { const query = document.getElementById('search-input').value.trim(); const resultsContainer = document.getElementById('search-results'); if (!query) { resultsContainer.innerHTML = "<p>请输入搜索关键词</p>"; return; } try { const response = await fetch( `https://api.bing.microsoft.com/v7.0/custom/search?q=${encodeURIComponent(query)}&customconfig=${CUSTOM_CONFIG_ID}&mkt=${MARKET}`, { headers: { 'Ocp-Apim-Subscription-Key': API_KEY } } ); if (!response.ok) throw new Error(`请求失败:${response.status}`); const data = await response.json(); // 渲染搜索结果 if (data.webPages?.value.length) { let resultsHtml = '<h3>搜索结果</h3><ul>'; data.webPages.value.forEach(item => { resultsHtml += `<li><a href="${item.url}" target="_blank">${item.name}</a><p>${item.snippet}</p></li>`; }); resultsHtml += '</ul>'; resultsContainer.innerHTML = resultsHtml; } else { resultsContainer.innerHTML = "<p>未找到匹配结果</p>"; } } catch (error) { resultsContainer.innerHTML = `<p>搜索出错:${error.message}</p>`; } } </script>
注意事项
- 确保Azure订阅已启用Bing Custom Search v7服务
Custom Config ID可在Azure门户的Bing Custom Search资源中获取- API密钥需从Azure资源的「密钥和终结点」页面复制
内容的提问来源于stack exchange,提问作者IDAutomationUser
相关产品推荐
相关产品推荐

