一個簡單的Ajax實例:選擇一部著作,會通過 Ajax 實時獲得相關的名字。
把4個html文件放到 web站點 的同一個文件下。
index.html
復制代碼 代碼如下:
html>
head>
meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
title>一個簡單的不涉及服務器的Ajax實例/title>
script type="text/javascript">
// 聲明一個引用 XMLHttpRequest 的變量
var xhr = null;
// 選擇一個著作時調用的函數
function updateCharacters() {
var selectShow = document.getElementById("selShow").value;
if (selectShow == "") {
document.getElementById("divCharacters").innerHTML = "";
return ;
}
// 實例化一個 XMLHttpRequest 對象
if (window.XMLHttpRequest) {
// 非IE
xhr = new XMLHttpRequest();
} else {
// IE
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = callbackHandler;
url = selectShow + ".html";
xhr.open("post", url, true);
xhr.send(null);
}
// this is the function that will repeatedly be called by our
// XMLHttpRequest object during the life cycle of request
function callbackHandler() {
if (xhr.readyState == 4) {
document.getElementById("divCharacters").innerHTML = xhr.responseText;
}
}
/script>
/head>
body>
我們的第一個Ajax實例
br>/br>
選擇一個名著:
br>
select onchange="updateCharacters();" id="selShow">
option value="">/option>
option value="xyj">西游記/option>
option value="hlm">紅樓夢/option>
option value="shz">水滸傳/option>
option value="sgyy">三國演義/option>
/select>
br>/br>
返回,名著中主要任務:
br>
div id="divCharacters">
select>
/select>
/div>
/body>
/html>
xyj.html
復制代碼 代碼如下:
select>
option>唐僧/option>
option>孫悟空/option>
option>豬八戒/option>
option>唐僧/option>
option>觀音姐姐/option>
option>西天如來/option>
/select>
hlm.html
復制代碼 代碼如下:
select>
option>賈寶玉/option>
option>林黛玉/option>
option>薛寶釵/option>
/select>
shz.html
復制代碼 代碼如下:
select>
option>林沖/option>
option>李逵/option>
option>宋江/option>
option>時遷/option>
/select>
sgyy.html
復制代碼 代碼如下:
select>
option>劉備/option>
option>關羽/option>
option>張飛/option>
option>曹操/option>
option>小喬/option>
option>諸葛亮/option>
/select>