zoukankan      html  css  js  c++  java
  • 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);
        }

    效果:

  • 相关阅读:
    -_-#【缓存】Content-Type 错误
    ♫【事件】事件处理程序
    -_-#【Node】Express 400 Error: ENOENT, open
    【JS】定位
    【JS】壹零零壹
    洛谷—— P1018 乘积最大
    洛谷—— P1017 进制转换
    洛谷——P1011 车站
    洛谷——P2241 统计方形(数据加强版)
    洛谷——P1548 棋盘问题
  • 原文地址:https://www.cnblogs.com/javayuan/p/5386751.html
Copyright © 2011-2022 走看看