javascript请求servlet实现ajax

ajax请求是一种无刷新式的用户体验,可以发送GET和POST两种异步请求,现记录如下:

GET请求:

function sendRequestByGet(){
          //定义异步请求对象
        var xmlReq;
        //检测浏览器是否直接支持ajax
        if(window.XMLHttpRequest){//直接支持ajax
            xmlReq=new XMLHttpRequest();
        }else{//不直接支持ajax
            xmlReq=new ActiveObject('Microsoft.XMLHTTP');
        }
        
          //设置回调函数
          xmlReq.onreadystatechange=function(){
              if (xmlReq.readyState==4&&xmlReq.status==200) {
                  //获取服务器的响应值
                var result=xmlReq.responseText;
                  //后续操作
                  alert(result);
            }
          };
          
          //创建异步get请求
          var url="Hello?name=zhangsan";
          xmlReq.open("GET",url,true);
          //发送请求
          xmlReq.send(null);
      }

POST请求:

function sendRequestByPost(){
          //定义异步请求对象
        var xmlReq;
        //检测浏览器是否直接支持ajax
        if(window.XMLHttpRequest){//直接支持ajax
            xmlReq=new XMLHttpRequest();
        }else{//不直接支持ajax
            xmlReq=new ActiveObject('Microsoft.XMLHTTP');
        }
        
          //设置回调函数
          xmlReq.onreadystatechange=function(){
              if (xmlReq.readyState==4&&xmlReq.status==200) {
                  //获取服务器的响应值
                var result=xmlReq.responseText;
                  //后续操作
                  alert(result);
            }
          };
          
          //创建异步Post请求
          var url="Hello";
          xmlReq.open("POST",url,true);
          xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
          //发送请求
          var data="name=lisi";
          xmlReq.send(data);
      }

ajax请求的servlet:

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String name=req.getParameter("name");
        PrintWriter out = resp.getWriter();
        out.print(name);
    }

效果:

原文地址:https://www.cnblogs.com/javayuan/p/5386751.html