Github代码地址

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

}

 

 

 

 

 

 

 
posted @ 2016-12-27 11:46  @小葱拌豆腐  阅读(683)  评论(0编辑  收藏  举报

霸气