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使用里的页面代码。

原文地址:https://www.cnblogs.com/wuxun1997/p/7593293.html