zoukankan      html  css  js  c++  java
  • Ajax的初级使用

    、AJAX简介(本文的例子都使用的是原生的ajax)
      老技术新用法
    、异步和同步区别
    、XMLHttpRequest对象(面试题)
    属性:
      readyState:  

        0:未初始化

        1open方法已经调用了

        2send方法已经调用了

        3:接收到了响应消息头,但没有接收到正文

        4:接收到了响应正文。响应结束

      responseText:只读的。返回的是String

        作用:接收服务器返回的文本类型的正文数据。

      responseXML:只读的。返回的是Document对象(JS中文档模型)

        作用:接收服务器返回的XML类型的正文数据。

      status:只读的。返回的是short

        作用:接收服务器返回的响应状态码

      statusText:只读的。返回的是String

        作用:接收服务器返回的响应吗描述

    方法:

    l open(String method,String url,boolean async):建立与服务器的链接。

      method:请求方式。GET|POST

      url:请求的服务器地址。

      async:是否是异步。true是异步的。默认就是true

    l send(String data):发出请求。data参数是请求正文的内容数据。

    l setRequestHeader(String headerName,String headerValue):设置请求消息头。

    l getAllResponseHeaders():返回所有的响应消息头。是一个String字符串。

    l getResponseHeader(headerName):返回指定头的值。是一个String字符串。

    事件处理器:onreadystatechange:执向一个函数。XMLHttpRequest对象的readyState的每次变化都会触发onreadystatechange指向的事件处理器。

    、GET和POST请求的发送
    、服务器端返回的数据类型:
      XML: 返回的是xml对象
      JSON:返回的是文本类型,需要转换

    编码步骤:

     1 function getXHR() {
     2     var xmlHttp;
     3 
     4     try {
     5         // Firefox, Opera 8.0+, Safari
     6         xmlHttp = new XMLHttpRequest();
     7     } catch (e) {
     8 
     9         // Internet Explorer
    10         try {
    11             xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    12         } catch (e) {
    13 
    14             try {
    15                 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    16             } catch (e) {
    17                 alert("您的浏览器不支持AJAX!");
    18                 return false;
    19             }
    20         }
    21     }
    22     return xmlHttp;
    23 }
    util.js
     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 
     3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     4 <html>
     5   <head>
     6     <title>AJAX的编码步骤:测试异步交互是可行的</title>
     7     
     8     <meta http-equiv="pragma" content="no-cache">
     9     <meta http-equiv="cache-control" content="no-cache">
    10     <meta http-equiv="expires" content="0">
    11     <!--
    12     <link rel="stylesheet" type="text/css" href="styles.css">
    13     -->
    14     <script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>
    15     <script type="text/javascript">
    16         window.onload=function(){
    17             //window.onload是一个事件,当文档加载完成之后触发该事件
    18             document.getElementById("bt1").onclick=function(){
    19                 //发出异步请求:步骤
    20                 
    21                 //1、得到xhr(XMLHttpRequest)对象
    22                 var xhr = getXHR();
    23                 //2、注册状态变化监听器
    24                 xhr.onreadystatechange=function(){
    25                     //做出具体的处理
    26                     if(xhr.readyState==4){//接收到了响应正文。响应结束
    27                         if(xhr.status==200){//200:服务器成功返回页面
    28                             alert("服务器已经响应结束了,去看看吧");
    29                         }
    30                     }
    31                 }
    32                 //3、建立与服务器的链接
    33                 //如果访问的地址相同,浏览器就不会真正的发出请求      ?time="+new Date().getTime()
    34                 xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo1?time=");
    35                 //4、向服务器发出请求
    36                 xhr.send(null);//没有正文
    37             }
    38         }
    39     </script>
    40   </head>
    41   
    42   <body>
    43     <input id="bt1" type="button" value="点我呀"/>
    44     <%--
    45         不论type是什么类型,只要单击鼠标就会执行,window.load=function事件
    46       --%>
    47   </body>
    48 </html>
    View Code

    一个验证用户名是否存在例子:(理解POST和GET提交时send方法传值的区别)

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 
     3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     4 <html>
     5   <head>
     6     <title>检测用户名是否可用</title>
     7     
     8     <meta http-equiv="pragma" content="no-cache">
     9     <meta http-equiv="cache-control" content="no-cache">
    10     <meta http-equiv="expires" content="0">
    11     <script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>
    12     <!--
    13     <link rel="stylesheet" type="text/css" href="styles.css">
    14     -->
    15     <script type="text/javascript">
    16         window.onload=function(){
    17             document.getElementById("username").onblur=function(){//失去焦点
    18                 if(this.value==""){
    19                     alert("请输入用户名");
    20                     this.focus();//恢复焦点
    21                     return;
    22                 }
    23                 //发出异步请求
    24                 var xhr = getXHR();
    25                 xhr.onreadystatechange=function(){
    26                     if(xhr.readyState==4){
    27                         if(xhr.status==200){
    28                             
    29                             document.getElementById("msg").innerHTML=xhr.responseText;
    30                             //responseText接收服务器返回的文本类型的正文数据。
    31                             //放到名为msg的span(属于一个行内元素)中
    32                         }
    33                     }
    34                 }
    35                 /*GET提交时,在send中传值是不起作用的;
    36                 xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo2?username="+this.value+"&time="+new Date().getTime());
    37                 xhr.send(null);
    38                 */
    39                 
    40                 //
    41                 xhr.open("POST","${pageContext.request.contextPath}/servlet/ServletDemo2?time="+new Date().getTime());
    42                 //设置请求消息头:告知客户端提交的正文的MIME类型
    43                 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    44                 xhr.send("username="+this.value);
    45             }
    46         }
    47     </script>
    48   </head>
    49   
    50   <body>
    51     <form action="" method="post">
    52         用户名:<input type="text" id="username" name="username"/><span id="msg"></span><br/>
    53         密码:<input type="password" id="password" name="password"/><br/>
    54         <input type="submit" value="注册"/>
    55     </form>
    56   </body>
    57 </html>
    页面
     1 package com.itheima.servlet;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.http.HttpServlet;
     7 import javax.servlet.http.HttpServletRequest;
     8 import javax.servlet.http.HttpServletResponse;
     9 
    10 public class ServletDemo2 extends HttpServlet {
    11     private String usernames[] = {"admin","wzhting"};//预先存在的用户名,也可连接数据库取;此处只是为了说明ajax做了简化处理
    12 
    13     public void doGet(HttpServletRequest request, HttpServletResponse response)
    14             throws ServletException, IOException {
    15         String username = request.getParameter("username");
    16         boolean b = false;//是否可用
    17         for(String s:usernames){
    18             if(s.equals(username)){
    19                 b = true;
    20                 break;
    21             }
    22         }
    23         
    24         response.setContentType("text/html;charset=UTF-8");
    25         if(b){
    26             response.getWriter().write("<font color='red'>用户名不可用</font>");
    27         }else{
    28             response.getWriter().write("<font color='green'>用户可用</font>");
    29         }
    30         
    31     }
    32 
    33     public void doPost(HttpServletRequest request, HttpServletResponse response)
    34             throws ServletException, IOException {
    35         doGet(request, response);
    36     }
    37 
    38 }
    ServletDemo2

    一个理解(利用jsp页面返回数据)例子:

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 
     3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     4 <html>
     5   <head>
     6     <title>显示所有的商品</title>
     7     
     8     <meta http-equiv="pragma" content="no-cache">
     9     <meta http-equiv="cache-control" content="no-cache">
    10     <meta http-equiv="expires" content="0">
    11     <script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>
    12     <!--
    13     <link rel="stylesheet" type="text/css" href="styles.css">
    14     -->
    15     <style type="text/css">
    16         .odd{
    17             background-color: #c3f3c3;
    18         }
    19         .even{
    20             background-color: #f3c3f3;
    21         }
    22     </style>
    23     <script type="text/javascript">
    24         var flag = false;
    25         window.onload=function(){
    26             document.getElementById("bt1").onclick=function(){
    27                 //发出异步请求
    28                 var xhr = getXHR();
    29                 xhr.onreadystatechange=function(){
    30                     if(xhr.readyState==4){
    31                         if(xhr.status==200){
    32                             if (flag == false) {
    33                                 document.getElementById("d1").innerHTML=xhr.responseText;//  文本类型 text/*
    34                                 flag = true;
    35                             } else {
    36                                 document.getElementById("d1").innerHTML="";
    37                                 flag = false;
    38                             }
    39                         }
    40                     }
    41                 }
    42                 xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo3?time="+new Date().getTime());
    43                 xhr.send(null);
    44             }
    45         }
    46     </script>
    47   </head>
    48   
    49   <body>
    50     <input type="button" id="bt1" value="显示商品"/>
    51     <hr/>
    52     <div id="d1"></div>
    53   </body>
    54 </html>
    主页面
     1 package com.itheima.servlet;
     2 
     3 import java.io.IOException;
     4 import java.util.ArrayList;
     5 import java.util.List;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 import com.itheima.domain.Product;
    13 
    14 public class ServletDemo3 extends HttpServlet {
    15     private List<Product> products = new ArrayList<Product>();
    16     public void init() throws ServletException {
    17         products.add(new Product(1, "充气筒", 20));
    18         products.add(new Product(2, "三国杀", 10));
    19         products.add(new Product(3, "扑克", 10));
    20         products.add(new Product(4, "洗衣粉", 10));
    21         products.add(new Product(5, "肥皂", 7));
    22     }
    23 
    24     public void doGet(HttpServletRequest request, HttpServletResponse response)
    25             throws ServletException, IOException {
    26         request.setAttribute("products", products);
    27         request.getRequestDispatcher("/listProducts.jsp").forward(request, response);
    28         //jsp页面因为是先编译成servlet在运行的,而servlet中的jsp页面就变成了如下形式的代码
    29         //out.write("<html>
    ");
    30         //所以response的是整个jsp页面
    31     }
    32 
    33     public void doPost(HttpServletRequest request, HttpServletResponse response)
    34             throws ServletException, IOException {
    35         doGet(request, response);
    36     }
    37 
    38 }
    ServletDemo3
     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     4 <html>
     5   <head>
     6     <title>title</title>
     7     
     8     <meta http-equiv="pragma" content="no-cache">
     9     <meta http-equiv="cache-control" content="no-cache">
    10     <meta http-equiv="expires" content="0">
    11     <!--
    12     <link rel="stylesheet" type="text/css" href="styles.css">
    13     -->
    14     
    15   </head>
    16   
    17   <body>
    18     <table border="1" width="438">
    19         <tr>
    20             <th>编号</th><%-- th比表示标题的一格,会自动加黑加粗 --%>
    21             <th>名称</th>
    22             <th>单价</th>
    23         </tr>
    24         <c:forEach items="${products}" var="p" varStatus="vs">
    25             <tr class="${vs.index%2==0?'odd':'even' }">
    26                 <td>${p.id}</td>
    27                 <td>${p.name}</td>
    28                 <td>${p.price}</td>
    29             </tr>
    30         </c:forEach>
    31     </table>
    32   </body>
    33 </html>
    返回数据的jsp页面

    结果表明:jsp页面因为是先编译成servlet再运行的,故jsp页面会变成了如下形式的代码:

        out.write("<html>
    ");
         out.write("	<head>
    ");
         out.write("		<title>title</title>
    ");
         out.write("	</head>
    ");
         out.write("	<bodystyle="background-color:lightblue">
    ");
         out.write("
    ");
       ……

    //所以jsp页面可以返还给xhr.responseText;即使servlet中没有response.getWriter().write("……");

     
     
     
     
     
     
     
     
     
  • 相关阅读:
    LINQ 笔记
    关于:last-child的一点见解
    webpack 配置IP 和端口号
    echarts.制作中国地图,点击对应的省市链接到该省份的详细介绍
    关于offsetWidth innerWidth的使用
    关于mobiscroll插件的使用
    关于取url或者微信中参数的js
    上传图片
    使用默认图片替代某张图为空时的情况
    在数组中计算和的最大最小值
  • 原文地址:https://www.cnblogs.com/mmzs/p/7755728.html
Copyright © 2011-2022 走看看