以下是一個以原生 XMLHttpRequest 實作的歌詞查詢範例,重點在於跨瀏覽器建立請求物件、以 GET 傳送參數,並把回應內容寫回頁面的指定區域,全程不刷新頁面。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>歌詞查詢</title>
</head>
<body>
<style type="text/css">
body {
background-color: #FFFFFF;
font-size: 85%;
font-family: Verdana;
margin-top: 10px;
margin-left: 10px;
}
a:link { color: #3737c8 }
a:active { color: #f00 }
a:visited { color: #639 }
</style>
核心在於三層 try/catch 的降級:先嘗試 Mozilla 系的 XMLHttpRequest,失敗則改用 IE 的 ActiveX,並在 Msxml2.XMLHTTP 與 Microsoft.XMLHTTP 兩個版本之間再降級一次。
<script language="Javascript">
var http_request = false;
function send_request(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla 系瀏覽器
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) { // 指定回應的 MIME 類型
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) { // 建立失敗
window.alert("無法建立 XMLHttpRequest 物件。");
return false;
}
http_request.onreadystatechange = processRequest;
http_request.open("GET", url, true); // 非同步
http_request.send(null);
}
以 readyState == 4 判斷請求結束,再以 status == 200 確認成功,然後把 responseText 寫入結果區。
function processRequest() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
document.getElementById("result").innerHTML = http_request.responseText;
} else {
alert("您請求的頁面發生異常。");
}
}
}
查詢前先檢查輸入是否為空,若為空則提示並把焦點移回輸入框;否則先顯示「正在查詢」的過渡訊息,再把關鍵字以 escape() 編碼後拼進查詢字串。
function DOSearch() {
var f = document.form1;
var geci = f.geci.value;
if (geci == "") {
window.alert("請輸入要查詢的歌曲名稱。");
f.geci.focus();
return false;
} else {
document.getElementById("result").innerHTML = "正在查詢,請稍候";
send_request('https://www.example.com/getgeci.aspx?m=' + escape(geci));
}
}
function submitForm() {
if (window.event.keyCode == 13) { DOSearch(); }
}
</script>
<form id="form1" name="form1" method="post" action="">
<p style="font-size:18px; color:#FF0000">歌詞線上免費查詢</p>
請輸入歌曲名:
<input name="geci" type="text" id="geci" value="" size="60"
maxlength="50" onKeyDown="submitForm()" />
<input type="button" name="search" value="查詢歌詞" onClick="DOSearch()" /><br />
<span id="result"></span>
</form>
</body>
</html>
第一,中文參數一定要編碼,且前後端字元集要一致(此例頁面宣告為 gb2312),否則會出現亂碼。第二,用 GET 傳中文時部分舊瀏覽器對長度與編碼處理不佳,資料量一大就該改走 POST 並設定 Content-type: application/x-www-form-urlencoded。第三,直接以 innerHTML 塞入伺服器回傳的文字,等同把內容當成 HTML 執行,正式環境務必改為轉義後輸出或改用 textContent,避免 XSS 風險。