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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值