王雨的JavaScript練習03---Ajax初體驗

AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。html

AJAX 不是新的編程語言,而是一種使用現有標準的新方法。編程

AJAX 最大的優勢是在不從新加載整個頁面的狀況下,能夠與服務器交換數據並更新部分網頁內容。瀏覽器

AJAX 不須要任何瀏覽器插件,但須要用戶容許JavaScript在瀏覽器上執行。服務器

html:app

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="new"></div>
<script src="script/addLoadEvent.js"></script>
<script src="script/getHTTPObject.js"></script>
<script src="script/getNewContent.js"></script>
</body>
</html>

js:異步

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function getHTTPObject() {
    if (typeof XMLHttpRequest == "undefined")
        XMLHttpRequest = function () {
            try { return new ActiveXObject("Msxml2,XMLHTTP.6.0"); }
            catch (e) {}
            try { return new ActiveXObject("Msxml2,XMLHTTP.3.0"); }
            catch (e) {}
            try { return new ActiveXObject("Msxml2,XMLHTTP"); }
            catch (e) {}
            return false;
        }
        return new XMLHttpRequest();
}

function getNewContent() {
    var request = getHTTPObject();
    if (request){
        request.open("GET","example.txt",true);
        request.onreadystatechange = function () {
            if (request.readyState == 4){
                var para = document.createElement("p");
                var txt = document.createTextNode("request.responseText");
                para.appendChild(txt);
                document.getElementById("new").appendChild(para);
            }
        };
        request.send(null);
    }else {
        alert('抱歉,你的瀏覽器不支持XMLHttpRequest')
    }
}
addLoadEvent(getNewContent);
相關文章
相關標籤/搜索