Ajax基础

第一步:创建Servlet基础

 

第二步:

1.创建XmlGttpRequest对象

2.发送Ajax请求

3.处理服务器响应

<body>
    <input id="btnLoad" type="button" value="加载"/>
    <div id="divContent"></div>

    <script>
        document.getElementById("btnLoad").onclick = function (){
            //1.创建XmlHttpRequest对象
            var xmlhttp;
            if (window.XMLHttpRequest){
                xmlhttp=new XMLHttpRequest();
            }else {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            //2.发送ajax请求
            xmlhttp.open("Get","/content");
            xmlhttp.send();
            //3.处理服务器响应
            xmlhttp.onreadystatechange=function ()//事件用于监听ajax的执行过程
            {
                if (
                    xmlhttp.readyState==4//这个属性用于说明XMLHttpRequest的当前状态,4代表响应文本已被接收
                    &&xmlhttp.status==200//代表服务器当前响应的状态码,200代表成功
                ){
                    //获取响应体的文本
                    var responseText = xmlhttp.responseText;
                    //对服务器结果进行处理
                    document.getElementById("divContent").innerHTML =
                        document.getElementById("divContent").innerHTML+"</br>"+responseText;
                }
            }
        }
    </script>
</body>

 补充:对应的类对象-->用于提供响应体文本

@WebServlet("/content")
public class ContentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("<b style='color:red'>I'm Server Content</b>");
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值