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);
        }

    效果:

  • 相关阅读:
    VSS部署手册
    正则表达式学习(二)
    完全卸载oracle11g步骤
    c#中 命令copy 已退出,返回值为1
    Windows 64位下装Oracle 11g,PLSQL Developer的配置问题,数据库处显示为空白的解决方案
    ora01033和ora12560错误的解决方案
    C#DLL加密保护
    ocslive.conf
    ASP.NET中文乱码问题的解决
    Creating a very simple autorestore USB stick clonezilla
  • 原文地址:https://www.cnblogs.com/javayuan/p/5386751.html
Copyright © 2011-2022 走看看