一個最簡單的Ajax實例

var $ = function(id) {
    return document.getElementById(id);
}
//創建一個XMLHttpRequest對象
var createXHR = function() {
    var xhr = false;
    try {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            xhr = false;
        }
    }
    if (!xhr && typeof XMLHttpRequest != "undefined") {
        xhr= new XMLHttpRequest();

    }

   if(!xhr){

       alert("您的瀏覽器不支持ajax");

   }

    return xhr;
}
//js處理服務器的響應
var updatePage = function(xhr) {
    if (xhr.readyState == 4) {
        var response = xhr.responseText;
        alert(response);
    }
}
//使用創建的XMLHttpRequest實例與服務器進行連接
function callServer() {
    var param = $("param").value;
    //Only go if there are values for both fields
    if ((city == null))
        return;
    if ((state == null))
        return;
    //Build the URL to connect to
    var url = "/script/getZipCode.jsp?param=" + escape(param);
    //Open a connection to the server
    var xhr = createXHR();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = updatePage;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章