本實例示範如何透過原生 AJAX 在不刷新整頁的情況下獲取內容並顯示到頁面上。
點擊按鈕查看效果:
核心代碼如下:
<div id="ajax_keleyi_com"></div>
<input type="button" value="Ajax獲取內容" onclick="startAjaxRequest()" />
<script>
var xmlHttp;
function createXMLHttpRequest(){
if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function startAjaxRequest(){
var host = 'https:///zliao/g/content/g1.htm';
createXMLHttpRequest();
xmlHttp.open('GET', host, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send('');
}
function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var keleyi_g1 = xmlHttp.responseText;
document.getElementById("ajax_keleyi_com").innerHTML = keleyi_g1;
}
}
}
</script>
它的實現思路分為三步:先透過 createXMLHttpRequest() 兼顧 IE 的 ActiveXObject 與標準瀏覽器的 XMLHttpRequest 來創建對象;再用 open() 以 GET 方式發起異步請求;最後在 onreadystatechange 中判斷 readyState == 4(請求完成)且 status == 200(成功),把返回的 responseText 寫入目標元素。