javascript基礎 AJAX簡單demo 2017年1月29日

function prepareForms() {
    for(var j=0 ; j<document.forms.length ; j++){
        var this_forms = document.forms[j];
        resetFields(this_forms);
         this_forms.onsubmit = function () {
             if(!validateForm(this)) return false; //進行瀏覽器端表單驗證
             var article = document.getElementsByTagName("article")[0];
             if(submitFormWithAjax(this,article)) return false; //代表防止重複提交 實際的提交已經完成
            return true;
         }
    }
}

首先 通過表單的提交事件調用相應的驗證方法 和ajax提交方法 如果說ajax提交成功 返回false 攔截提交事件 如果ajax失敗 則正常提交

function displayAjaxLoading(element) {
    while(element.hasChildNodes()){
        element.removeChild(element.lastChild); //如果還有子節點 重複刪除 直到內部爲空
    }
    var content = document.createElement("img");
    content.setAttribute("src","images/loading.gif");
    content.setAttribute("alt","loading....");
    element.appendChild(content);
} //拿到元素 清空內部 並添加一個img

function submitFormWithAjax(whichform,thetarget) {
    var request = getHTTPObject();
    if(!request){return false ;}
    displayAjaxLoading(thetarget);//調用加載方法
    var dataParts = [];
    var element; //提前創建要用的容器
    for(var i=0 ; i<whichform.elements.length ; i++){
        element = whichform.elements[i];
        dataParts[i] = element.name + "=" +encodeURIComponent(element.value) //把元素的名字和值轉化成URL編碼放入容器中
    }
    var data = dataParts.join("&"); //把數組轉化成一串字符串 每個項目之間用&連接
    request.open("post",whichform.getAttribute("action"),true); //向表單目標地址準備提出名爲post的請求
    request.setRequestHeader("content-type","application/x-www-form-urlencoded");//設置頭部信息
    //獲取請求後就會調用一下的 方法 算是一個觸發器 服務器會執行以下內容
    request.onreadystatechange = function () {
        if(request.readyState == 4){
            if(request.status == 200 || request.status == 0){
                var matches = request.responseText.match(/<article>([\s\S]+)<\/article>/) //捕獲文本
                if(matches.length>0){
                    thetarget.innerHTML = matches[1]; //正則表達式返回0爲包含<article> 1爲不包含的版本
                }
                else {
                    thetarget.innerHTML = "<p>sorry not find</p>";
                }
            }
            else {
                thetarget.innerHTML = "<p>" + request.statusText + "</p>";
            }
        }
    }

    request.send(data); //對目標服務器發送請求
    return true;//代表函數執行完畢
}

讓我們分步來查看具體做了什麼事情
第一 獲取了一個請求對象
第二 調用display方法 讓頁面刪除article下的所有元素並放上load動畫
第三 創建URL編碼的請求 用數組存放 一項裏面爲name和被URL轉義的value 然後把他每項通過&連接 組成一個完整的字符串
第四 設置了請求的基本屬性 比如命名 目標地址 頭文件
第五 創建一個監聽程序 監聽請求 如果成功則把響應的html填入到目標article中
第六 正式發送請求 成功返回ture

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章