zoukankan      html  css  js  c++  java
  • ajax

    01.创建jsp页面

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        
        <!-- 
           传统的web和ajax的区别:
       01.发送方式不同:
                  传统的web同步发送!
             ajax异步发送!
       02.服务器响应不同:
                 传统的web响应的是一整个页面!
             ajax响应的只是用户需要的数据!
       03. 客户端处理的方式不同
                传统的web必须等待整个网页加载完毕,才能继续操作!
          ajax可以动态的刷新局部内容,不影响用户的其他操作!  
          
    Ajax (Asynchronous javaScript  and  xml)   一种局部刷新的技术!
     包含了 js xml json...等技术! 
     
    核心对象:XMLHttpRequest  
     常用的方法:
       01.open(method,url,async) 
          method:请求的方式
          url:请求的地址,get请求时可以拼接参数
          async:是否异步交互
       02.send(data)
           data:get请求时!可以是null ,也可以不写   !
       03.setRequestHeader(String header,String value):设置http请求信息
       04.getResponseHeader(String header):获取指定响应的信息
    
    事件:回调函数  onreadystatechange   
    常用的属性:
     readyState: XMLHttpRequest的状态码
      0:没有完成初始化
      1:请求准备好了,可以开始发送
      2:请求发送完成
      3:开始读取相应
      4: 响应完成
      
     status:http的状态码
      200:服务器正确返回响应
      403:没有访问权限
      404:请求的资源不存在
      500:服务器内部错误!
      ......
      
     responseText:以文本的形式获取响应的内容!
     responseXML:将xml格式的响应内容转换成dom对象返回!
    --> <script type="text/javascript" src="js/jquery-1.12.4.js"></script> <script type="text/javascript"> //输入框失去焦点时 触发的事件 function validate(){ var name= $("[name='userName']").val(); //js中是.value; if(name==null||name==""){ $("div").html("<span style='color:red'>用户名不能为空</span>"); }else{ //01.创建XMLHttpRequest核心对象 var xhr=createXhr(); //02.设置回调函数 xhr.onreadystatechange=callBack; //03.初始化xhr的组件 var url="ValidateServlet?name="+name; xhr.open("GET",url,true); //04.发送请求 get请求的时候 可以是null 也可以不写参数 xhr.send(null); //回调函数 function callBack(){ if(xhr.readyState==4&&xhr.status==200){ //代表响应正确返回 var data= xhr.responseText; //文本的方式获取后台响应的数据 if (data.match("true")) {//data=="true" $("div").html("<span style='color:red'>用户名已经被占用!!!</span>"); }else{ $("div").html("<span style='color:red'>用户名可以正常使用!!!</span>"); } } } } } //创建XMLHttpRequest核心对象 function createXhr(){ if(window.XMLHttpRequest){ //高版本的浏览器 return new XMLHttpRequest(); }else{ //低版本 return new ActiveXObject("Microsoft.XMLHTTP"); } } </script> </head> <body> <input type="text" name="userName" onblur="validate();"> <div></div> <img alt="小猫咪" src="images/cat.jpg"> </body> </html>
    复制代码

    02.创建对应的servlet

    复制代码
    public class ValidateServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response); // 执行post请求
    
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("servlet  begin");
            // 获取前台name
            String name = request.getParameter("name");
            boolean flag = false;
            if ("admin".equals(name)) {
                flag = true; // 默认已经存在
            }
            // 把信息给前台
            PrintWriter pw = response.getWriter();
            pw.print(flag);
            pw.flush();
            pw.close();
            System.out.println("servlet  over");
        }
    
    }
    复制代码
    复制代码
    /**
    get方式配置组件
     xhr.open("GET","ValidateServlet?name="+name,true);
      xhr.send(null); 或者 xhr.send();
    post方式配置组件  
     xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      //04.发送请求  
      var data="name="+name+"&pwd="+"12354";
      xhr.send(data);  
    */
    复制代码

    03.jquery实现ajax

    复制代码
    /**
    使用jquery实现ajax!
    
    常用的属性:
     url:请求的地址
     type:请求的方式  默认是 get
     data:发送的数据
     dataType:预期服务器返回的类型
     beforeSend:发送请求之前调用的函数
     success:成功之后调用的函数
     error:失败调用的函数
     complete:请求完成后调用的函数(无论失败还是成功)
      
      $.ajax({
        url:"ValidateServlet",
        type:"get",
        data:"name="+name,
        dataType:"text",
        beforeSend:function(){
        
        },
        success:function(){
        
        },
        error:function(){
        
        }
        
      })
      
    
    */
    复制代码
    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'jquery.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    <script type="text/javascript" src="js/jquery-1.12.4.js"></script>
    <script type="text/javascript">
        $(function() {
            $("[name='userName']")
                    .blur(
                            function() { //输入框的失去焦点事件
                                var name = $("[name='userName']").val(); //获取用户的输入内容
                                if (name == null || name == "") {
                                    $("div")
                                            .html(
                                                    "<span style='color:red'>用户名不能为空</span>");
                                } else {
                                    $.ajax({ //使用jquery实现ajax技术
                                        url : "ValidateServlet", //请求的地址
                                        type : "get", //请求的方式 默认是get
                                        data : "name=" + name, //请求携带的参数
                                        dataType : "text", //预期服务器返回的数据格式
                                        beforeSend : function() { //请求发送之前触发的事件
                                            alert("请求正在发送......");
                                        },
                                        success : callBack, //data后台返回的数据   响应成功之后的事件
                                        error : function() { //响应失败之后的事件
                                            alert("出现错误........");
                                        }
                                    })
    
                                    //响应成功之后的事件
                                    function callBack(data) {
                                        if (data.match("true")) {//data=="true"
                                            $("div")
                                                    .html(
                                                            "<span style='color:red'>用户名已经被占用!!!</span>");
                                        } else {
                                            $("div")
                                                    .html(
                                                            "<span style='color:red'>用户名可以正常使用!!!</span>");
                                        }
                                    }
                                }
                            })
    
        })
    </script>
    
    </head>
    
    <body>
        <input type="text" name="userName">
        <div></div>
    </body>
    </html>
    复制代码
    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'json.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        <script type="text/javascript" src="js/jquery-1.12.4.js"></script>
        <script type="text/javascript">
                 $(function(){
                    //01.定义json格式的对象 并在div中输出
                    var  user={
                    "id":1,
                    "name":"小白",
                    "password":"123456"
                    };
                    $("#objectDiv").append("ID:"+user.id+"<br/>")
                    .append("name:"+user.name+"<br/>")
                    .append("password:"+user.password+"<br/>")
                   //02.定义json格式的字符串数组  并在ul和select中输出
                    var  array=["小黑","小白","小红"];
                    var  $arr=$(array);  //把数组转换成jquery对象
                    var  $arraySelect=$("#arraySelect"); //获取下拉框对象
                    //循环给下拉列表增加option
                     $arr.each(function(i){
                        $arraySelect.append("<option value='"+(i+1)+"'>" +this+"</option>");
                     })
                     //获取ul
                     var $ul=$("#arrayUl");
                     $arr.each(function(){
                          $ul.append("<li>" +this+"</li>");
                     }) 
                    //03.定义json格式的对象数组   放入到div中的table表格中
                    var userArrays=
                    [
                     {
                     "id":1,
                    "name":"小白",
                    "password":"123456"
                     },
                     {
                     "id":2,
                    "name":"小黑",
                    "password":"123456"
                     },
                     {
                     "id":3,
                    "name":"小红",
                    "password":"123456"
                     }];
                     //创建一个table表格
                   var  $table=$("<table border='1'></table>")
                   .append("<tr><td>编号</td><td>用户名</td><td>密码</td></tr>");
                     //遍历对象数组
                     $(userArrays).each(function(){
                        $table.append("<tr><td>"+this.id+"</td><td>"
                        +this.name+"</td><td>"+this.password+"</td></tr>");
                     })
                     //把表格放入到div中
                    $("#objectArray").append($table);
                 })
        </script>
        
      </head>
      
      <body>
        1:json格式的对象  &nbsp; &nbsp; &nbsp;
         <div id="objectDiv"></div><br/>
        2:json格式的字符串数组  &nbsp; &nbsp; &nbsp;   
         <select id="arraySelect"></select>
         <ul id="arrayUl"></ul><br/>
        3.json格式的对象数组&nbsp; &nbsp; &nbsp;
          <div id="objectArray"></div>
      
      
      </body>
    </html>
    复制代码

     json格式数据

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'object.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        <script type="text/javascript" src="js/jquery-1.12.4.js"></script>
        <script type="text/javascript">
            $(function(){
              $.ajax({
                 url:"UserServlet",
                 type:"get",
                 dataType:"json",
                 success:function(data){  //就收后台json格式的数据   之后在页面上显示
                    $("div").append("<span>姓名</span>&nbsp;&nbsp;&nbsp;<span>密码</span></br>");
                    $(data).each(function(i){
                      $("div").append("<span>"+data[i].name+"</span>&nbsp;&nbsp;&nbsp;<span>"+data[i].password+"</span></br>");
                    })
                  }
              })
            })
        </script>
      </head>
      <body>
       <div></div>
      </body>
    </html>
    复制代码
    复制代码
    public class UserServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response);
    
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setHeader("Content-Type", "text/html;charset=utf-8");
            User user1 = new User(1, "小白1", "123");
            User user2 = new User(2, "小白2", "1234");
            User user3 = new User(3, "小白3", "123456");
            List<User> users = new ArrayList<User>();
            users.add(user1);
            users.add(user2);
            users.add(user3);
    
            // 转换成json格式
            String json = JSON.toJSONString(users);
            System.out.println(json);
    
            PrintWriter pw = response.getWriter();
            pw.print(json);
            pw.flush();
            pw.close();
        }
    
    }
    复制代码
    复制代码
    /**
     * 
     * Ajax: 
     *   核心对象  XMLHttpRequest
     *   
     *   属性:
     *    readyState:  代表服务的响应信息
     *              0:请求没有初始化
     *                经过XMLHttpRequest.open(method,url,asyns) 状态变成1
     *                   method:请求的方式
     *                   url:服务器的地址
     *                   asyns:是否异步! true:异步   false:同步
     *              1:请求初始化     但是并没有访问服务器
     *                 通过XMLHttpRequest.send()建立连接
     *              2:请求已经发送
     *              3:处理请求信息
     *              4:请求完成  
     *              
     *   readyState的变化会触发onreadyStatechange,
     *   如果readyState==4,并且status==200代表请求成功!就可以渲染界面!
     * 
     *   get方式请求服务器的时候
     *   send() send(null)  send()中不能加别的参数!
     *   
     *   post方式请求服务器的时候
     *   send(数据信息)   
     *   而且要在open()之后加入
     *   xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     * 
     */
    复制代码
    readMe

    javaScript实现ajax

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      <script type="text/javascript">
         window.onload=function(){ 
         //点击按钮触发的事件
           btn.onclick=function(){
            //01.创建XMLHttpRequest核心对象  是全局对象
           var xhr=null;
           //根据不同的版本创建不同的核心对象
           if(window.XMLHttpRequest){//高版本
           xhr=new XMLHttpRequest;
           }else if(window.ActiveXObject){ //低版本
           xhr=new ActiveXObject("Microsoft.XMLHttp")
           }else{
             alert("拜拜!");
           }
           //02.设置回调函数
           xhr.onreadystatechange=function(){
           //判断状态码
             if(xhr.readyState==4&&xhr.status==200){
             //获取响应的数据
               myAjax.innerHTML+=xhr.responseText;
             }
           }
           //03.配置核心对象的组件 
            xhr.open("get", "hello.txt", true);
            //04.发送请求
            xhr.send();
           }
         }
      </script>
    
      </head>
      
      <body>
      <input type="button" id="btn"  value="点击加载">
        <div id="myAjax"></div>
        <img src="images/cat.jpg">
      </body>
    </html>
    复制代码
    index.jsp
    大家辛苦了!!!!abc
    对应的hello.txt文件

    验证用户名是否存在

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      <script type="text/javascript">
         window.onload=function(){ 
         //文本框失去焦点的事件
           userName.onblur=function(){
            //01.创建XMLHttpRequest核心对象  是全局对象
           var xhr=null;
           //根据不同的版本创建不同的核心对象
           if(window.XMLHttpRequest){//高版本
           xhr=new XMLHttpRequest;
           }else if(window.ActiveXObject){ //低版本
           xhr=new ActiveXObject("Microsoft.XMLHttp")
           }else{
             alert("拜拜!");
           }
           //根据用户的输入增加提示信息
           if(userName.value==""){
             msg.innerHTML="<div style='color:red'>用户名不能为空</div>";
           }else{
               //02.设置回调函数
           xhr.onreadystatechange=function(){
           //判断状态码
             if(xhr.readyState==4&&xhr.status==200){
             //获取响应的数据 判断是否存在该用户
               if(xhr.responseText.match(/ok/)){
                msg.innerHTML="<div style='color:green'>可以注册!1秒钟跳转到注册页面</div>";
                //设置定时函数
                setTimeout(function(){
                  location.href="success.jsp";
                },1000);
               }else if(xhr.responseText.match(/error/)){
                msg.innerHTML="<div style='color:red'>用户名已经存在!</div>";
               }else{
                msg.innerHTML="错误信息"+xhr.statusText;
               }
             }
           }
           /*get请求
            xhr.open("get", "do.jsp?userName="+userName.value, true);
            xhr.send();*/
            
            //post请求
             xhr.open("post", "do.jsp", true);
             xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
             xhr.send("userName="+userName.value);
            
           }
           }
         }
      </script>
    
      </head>
      
      <body>
      <input type="text" id="userName" name="userName"/>
        <div id="msg"></div>
      </body>
    </html>
    复制代码
    login.jsp
    复制代码
    <%
      //获取login界面的userName的值
      String name= request.getParameter("userName");
      //定义一个返回给前台的响应信息
      String  message="";
      if(name.equals("admin")){
        message="error";
      }else{
        message="ok";
      }
    
     //怎么把响应给前台????
     out.print(message);
    
    %>
    复制代码
    do.jsp
      <body>
       <h1>注册页面</h1>
      </body>
  • 相关阅读:
    The Python Standard Library
    Python 中的round函数
    Python文件类型
    Python中import的用法
    Python Symbols 各种符号
    python 一行写多个语句
    免费SSL证书(https网站)申请,便宜SSL https证书申请
    元宇宙游戏Axie龙头axs分析
    OLE DB provider "SQLNCLI10" for linked server "x.x.x.x" returned message "No transaction is active.".
    The operation could not be performed because OLE DB provider "SQLNCLI10" for linked server "xxx.xxx.xxx.xxx" was unable to begin a distributed transaction.
  • 原文地址:https://www.cnblogs.com/HHR-SUN/p/7208405.html
Copyright © 2011-2022 走看看