DIV CSS 佈局教程網

用 JavaScript 一次搜尋百度與必應的實作方法
編輯:關於JavaScript     

想同時比對兩家搜尋引擎的結果嗎?做法是:用一個頁面放搜尋框,按下按鈕後把同一組關鍵字分別提交給百度與必應,並讓兩個結果各自載入不同的框架(frame)中。這樣就能在同一個畫面左右並排比較。

整體結構

整個功能由兩個檔案組成,放在同一個資料夾中,開啟 index.htm 即可:

  • index.htm:以 frameset 切出上方查詢列(30%)與下方雙欄結果區(各 45%)。
  • keleyi.htm:查詢列本體,包含輸入框、按鈕與提交邏輯。

index.htm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>同時搜尋百度和必應</title>
<meta http-equiv="keywords" content="同時搜尋百度和必應">
<meta http-equiv="description" content="同時搜尋百度和必應">
</head>

<frameset rows="30%,70%">
<frame src="keleyi.htm">
</frame>
<frameset cols="45%,45%">
<frame id="baiduFrame" name="baiduFrame" src="images/baidu.jpg"></frame>
<frame id="bingFrame" name="bingFrame" src="images/baidu.jpg"></frame>
</frameset>
</frameset>

</html>

兩個結果框架各自有 name(baiduFrame、bingFrame),稍後表單就是靠這個名稱指定要提交到哪裡。初始 src 先指向一張示意圖,避免空白。

keleyi.htm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>同時搜尋百度和必應</title>
<meta http-equiv="keywords" content="同時搜尋百度和必應">
<meta http-equiv="description" content="同時搜尋百度和必應">

<script type="text/javascript">
function $(id) {
  return document.getElementById(id);
}

function mixSearch() {
  var okeyword = $("keyword");
  var oForm = $("searchForm");

  // 提交給百度,構造網址參數
  oForm.action = "https://www.baidu.com/s";
  okeyword.name = "wd";
  oForm.method = "get";
  oForm.target = "baiduFrame";
  oForm.submit();

  // 提交給 bing,構造網址參數
  oForm.action = "https://hk.bing.com/search";
  okeyword.name = "q";
  oForm.method = "get";
  oForm.target = "bingFrame";
  oForm.submit();
}
</script>
</head>

<body style="text-align: center;">
<form action="" id="searchForm" method="get" target="baiduFrame">
<input type="text" id="keyword" name="wd" value="" />
<input type="button" value="搜一下" onclick="mixSearch();" />
</form>
<hr />
</body>
</html>

運作原理拆解

關鍵在於同一個 <form> 被連續提交兩次,每次提交前改寫三個地方:

  1. form.action 換成不同引擎的搜尋端點。
  2. input.name 換成該引擎認得的參數名(百度用 wd,必應用 q)。
  3. form.target 換成對應的框架名稱,讓結果各自開在自己的窗格裡。

現代寫法的建議

這個範例用的是 HTML 4 的 frameset,該標籤在 HTML5 中已被移除,且對搜尋引擎與無障礙工具都不友善。若要在今日的專案實作類似功能,建議改用:

  • 以 <iframe> 取代 frameset,並用 CSS Grid/Flexbox 排版;注意多數搜尋引擎會以 X-Frame-Options 或 CSP 阻擋被嵌入。
  • 用 window.open(url, '_blank') 開啟兩個新分頁,避開嵌入限制。
  • 或直接串接各引擎的搜尋 API/改用 fetch 搭配後端代理,自行呈現結果。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved