Ajax異步調用http接口后刷新頁面


  使用Ajax的目的就是提高頁面響應速度,無需同步調用,無需整個頁面刷新。這里直接在html中使用js來實現:

先獲取XMLHttpRequest對象

    var xmlHttp;

    //創建一個xmlHttpRequest對象
    window.onload = function createxmlHttp() {
        try {
            //嘗試創建 xmlHttpRequest 對象,除 IE 外的瀏覽器都支持這個方法。  
            xmlHttp = new XMLHttpRequest();
        } catch (e) {
            try {
                //使用較新版本的 IE 創建 IE 兼容的對象(Msxml2.xmlHttp)。  
                xmlHttp = ActiveXObject("Msxml12.XMLHTTP");
            } catch (e1) {
                try {
                    //使用較老版本的 IE 創建 IE 兼容的對象(Microsoft.xmlHttp)。  
                    xmlHttp = ActiveXObject("Microsoft.XMLHTTP");
                } catch (e2) {
                    flag = false;
                }
            }
        }

        //判斷是否成功的例子:  
        if (!xmlHttp) {
            alert("creat XMLHttpRequest Object failed.");
        }
    }

 

  這里xmlHttp作為一個js的全家變量,后續方法需要用到。再看下怎么異步調用get方式的http請求:

    //調用http接口獲取接口內容
    function getMethodContent(method) {
        url = "/getMethod/" + method;
        xmlHttp.open("GET", url, true);
        xmlHttp.onreadystatechange = showContent;
        document.getElementById("interfaceName").value = method; //將接口名放入html指定div中
        xmlHttp.send();
    }

    //回調函數,顯示http響應結果
    function showContent() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                var text = xmlHttp.responseText; //這里獲得服務器返回的數據
                document.getElementById("interfaceBody").innerHTML = text; //將數據放入html指定div中
            } else {
                alert("response error code:" + xmlHttp.status);
            }
        }
    }

  

  這里通過回調函數showContent來局部刷新interfaceName和interfaceBody的值。

  post的方式:

    //新增、編輯接口
    function generateInterfaceEntity() {
        url = "/editMethod/" + document.getElementById("interfaceName").value;
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Content-type",
                "application/json;charset=UTF-8");
        xmlHttp.onreadystatechange = showActionResult;
        xmlHttp.send(document.getElementById("interfaceBody").innerHTML);
    }

    //回調函數,顯示action操作結果,刷新頁面
    function showActionResult() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                alert("operation success!");
                window.location.reload();
            } else {
                alert("operation failed! response error code:" + xmlHttp.status);
            }
        }
    }

 

  這里在新增、編輯后提示操作成功,接口通過reload來刷新整個頁面。完整頁面參見spring mvc+velocity使用里的頁面代碼。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM