Ajax---基础

一、Ajax基础
  1. Ajax简介
          Ajax=Asynchronous JavaScript And XML(异步的javaScript和XML)。
          Ajax不是一门新的编程语言,是一种用于创建快速动态网页的技术。
          通过与服务器进行少量数据交换,Ajax可以使网页实现异步更新。也即是在不重新加载整个页面的情况下,对网页的某个部分进行更新。
          而传统的网页(不使用Ajax)如果要更新内容,必须重载整个页面。浪费网络流量带宽。
    2. Ajax的工作原理
          通过一个实例,讲解Ajax的工作原理:
        1)新建一个AjaxTest的web应用,编辑index.html如下:
          <html>
               <head>
                    <script type="text/javaScript">
                         function loadXMLDoc( ){
                              
               var xmlhttp;
                  if (window.XMLHttpRequest)
               {
                    xmlhttp= new XMLHttpRequest();
               }else{
                    xmlhttp= new ActiveXObject("Microsoft.XMLHTTP" );
               }
               xmlhttp.onreadystatechange= function()//接收响应更新页面显示
               {
                   if (xmlhttp.readyState==4 && xmlhttp.status==200)
                  {
                       document.getElementById( "myDiv").innerHTML=xmlhttp.responseText;
                  }
              };
              xmlhttp.open( "GET","DealResServlet" ,true);
              xmlhttp.send();//发送请求
                         }
                    </script>
               </head>
               <body>
                    <div id="myDiv"><h3>Let Ajax change this text!</h3></div>
                    <button type="button" onclick="loadXMLDoc( )">changeContext</button>
               </body>
          </html>
        2)在src目录下新建一个Servlet处理请求:DealResServlet.java 
     代码如下: 
     package com.servlet;
 
     import java.io.IOException;
     import java.io.PrintWriter;
     import javax.servlet.ServletException;
     import javax.servlet.annotation.WebServlet;
     import javax.servlet.http.HttpServlet;
     import javax.servlet.http.HttpServletRequest;
     import javax.servlet.http.HttpServletResponse;
 
     @WebServlet(name="DealResServlet" ,urlPatterns = "/DealResServlet")
     public class DealResServlet extends HttpServlet {
            private static final long serialVersionUID = 1L;
 
            protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
                 PrintWriter out = response .getWriter();
                 out.write("hello Ajax" );
           }
     }
     部署web应用,在浏览器地址栏输入:http://localhost:8080/AjaxTest/index.html

点击按钮后,页面发送请求给服务器,对应的Servlet处理该请求,返回响应。

 
二、Ajax中的XMLHttpRequest对象:也即XHR对象
     XMLHttpRequest 对象是Ajax技术的基础也是主要对象,所有现在的浏览器均支持XMLHttpRequest对象(IE5、IE6使用ActiveXObject)
   1.  XMLHttpRequest 对象的创建
     所有现在的浏览器(IE7+、Firefox、Chrome、Safari、Opera)均内建了XMLHttpRequest对象
     varible = new XMLHttpRequest( );
     老版本的IE使用ActiveXObject对象:varible = new ActiveXObject("Microsoft.XMLHTTP");
     为了应对所有现在的浏览器,包括IE5、6,在使用XHR时,应该检查浏览器是否支持XMLHttpRequest对象,如果支持,创建XMLHttpRequest对象,如果不支持,则创建ActiveXObject:
     var xmlhttp;
     if(window.XMLHttpRequest ){
          xmlhttp = new XMLHttpRequest( );
     }else{
          xmlhttp = new  ActiveXObject("Microsoft.XMLHTTP" );
     }
    2. XMLHttpRequest请求
     XMLHttpRequest对象用于和服务器交换数据
     ---------------------------------------------------------------------------------------------------
     向服务器发送请求:
       将请求发送给服务器,使用XMLHttpRequest 对象的两个函数:open()和send()
       xmlhttp.open( "GET", "", true);
       xmlhttp.send( );
     
 ---------------------------------------------------------------------------------------------------
     GET还是POST的选择?
     与POST相比,GET更简单更快,在大多数情况下使用。
     在以下情况下,需使用POST方法:
     1)无法使用缓存文件(更新服务器上的文件或数据库)
     2)向服务器发送大量数据(POST没有数据量限制)
     3)发送包含未知字符的用户输入时,POST比GET更稳定更可靠
     ---------------------------------------------------------------------------------------------------
     GET请求
     xmlhttp.open("GET","url",true);
     xmlhttp.send( );
     ---------------------------------------------------------------------------------------------------
     在上面的例子,可能得到的是缓存的结果。
     为了避免这种情况,向URL添加一个唯一的ID。
     xmlhttp.open("GET","url?t="+Math.random( ),true);
     xmlhttp.send( );
     --------------------------------------------------------------------------------------------------
     如果希望通过GET请求发送消息,请向URL添加信息。
     xmlhttp.open("GET","url?name=zwbg&age=23”,true);
     xmlhttp.send( );
     实例:
     
          <html>
               <head>
                    <script type="text/javaScript">
                         function loadXMLDoc( ){
                              
               var xmlhttp;
                  if (window.XMLHttpRequest)
               {
                    xmlhttp= new XMLHttpRequest();
               }else{
                    xmlhttp= new ActiveXObject("Microsoft.XMLHTTP" );
               }
               xmlhttp.onreadystatechange= function()//接收响应更新页面显示
               {
                   if (xmlhttp.readyState==4 && xmlhttp.status==200)
                  {
                       document.getElementById( "myDiv").innerHTML=xmlhttp.responseText;
                  }
              };
              xmlhttp.open( "GET","DealResServlet2?name=zwbg&age=23" ,true);
              xmlhttp.send();//发送请求
                         }
                    </script>
               </head>
               <body>
                    <div id="myDiv"><h3>Ajax Info</h3></div>
                    <button type="button" onclick="loadXMLDoc( )">获取数据</button>
               </body>
          </html>
      其中DealResServlet2主要代码为:
     
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String name = request .getParameter("name");
            String age = request .getParameter("age");
            PrintWriter out = response .getWriter();
             out.write("name: " +name +"<br>" );
             out.write("age: " +age );
      }

 ---------------------------------------------------------------------------------------------------
     POST请求:
     一个简单的POST请求:
     xmlhttp.open("POST","url",true);
     xmlhttp.send( );
     如果需要向HTML表单那样POST数据,首先必须使用setRequestHeader( )来添加HTTP请求头。然后在send()方法中规定你希望发送的数据:
xmlhttp.open("POST","url",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");//发送的消息
 url--服务器上的文件
     open()方法的url参数是服务器上文件的地址:
     该文件可以是任何类型的文件,比如.txt .xml或者服务器脚本。.asp或者.php(在传回响应时能够执行任务)

  异步:-True或False
  Ajax指的是异步的js 和xml
  XMLHttpRequest对象如果是用于Ajax的话,其open()方法的asyn参数设置为true
  xmlhttp.open("GET","url",true);
  对于web程序员来讲,发送异步请求是一种进步,很多服务器执行的任务相当费时,Ajax出现之前,可能引起应用程序挂起或者停止(等待服务器响应)
  通过Ajax,Javascript无需等待服务器响应。而是:
     在等待服务器响应时执行其他脚本
     在响应就绪后对响应进行处理

Asyn = true
当使用asyn=true时,请规定在响应处于onreadystatechange事件中的就绪状态时执行的函数:
xmlhttp.onreadystatechange = function( )
{
     if( xmlhttp.readyState == 4&& xmlhttp.status==200)
     {
          document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
     }
}
xmlhttp.open("GET","",true);
xmlhttp.send( );

 Asyn=false
  一般不推荐使用aysn=false,但对于一些小的请求,也是可以的。
javaScript会等待服务器响应就绪后才继续执行。如果服务器繁忙或者缓慢,应用程序就会挂起或停止
注意:当aysn=false时,不要编写onreadystatechange函数,把代码放在send()语句后面即可。
xmlhttp.open("GET","",false);
xmlhttp.send( );
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
3.XMLHttpRequest响应
如果需要获取服务器的响应,使用XMLHttpRequest对象的responseText或者responseXML属性
responseText属性
如果服务器的响应不是XML,要使用responseText属性
responseText属性返回字符串形式的响应。
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;

responseXML属性
如果服务器的响应时xml,而且需要作为XML对象进行解析,这时要使用responseXML属性
响应返回.xml文件,解析此响应:
在Servlet中设置response.setContentType("text/xml;charset=utf-8");  告诉浏览器文档类型是xml,按照相应的规则解析。

4.Ajax--onreadystatechange事件
onreadystatechange事件:当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当readyState改变时,就会触发onreadystatechange事件
readyState属性存有XMLHttpRequest的状态信息
XMLHttpRequest对象的三个重要属性:
在onreadystatechange事件中,规定当服务器响应已做好被处理的准备时所执行的任务。
当readyState等于4且状态为200时,表示响应就绪:
xmlhttp.ononreadystatechange = function( ){
     if( xmlhttp.readyState==4&&xmlhttp.status==200)
     {
          document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
     }
};
三 Ajax在web中的简单应用实例:
AJAX用于创建动态性更强的应用程序:
实例:--当用户在输入框输入字符时,网页和web服务器进行通信

其中index.html为:
<html>
<head>
<script type="text/javascript" >
       function showHint(str)
      {
             var xmlhttp;
             if (str.length==0)
            {
                  document.getElementById( "txtHint").innerHTML="" ;
                   return;
            }
             if (window.XMLHttpRequest)
            { // code for IE7+, Firefox, Chrome, Opera, Safari
                  xmlhttp= new XMLHttpRequest();
            }
             else
            { // code for IE6, IE5
                  xmlhttp= new ActiveXObject("Microsoft.XMLHTTP" );
            }
            xmlhttp.onreadystatechange= function()
            {
                   if (xmlhttp.readyState==4 && xmlhttp.status==200)
                  {
                  document.getElementById( "txtHint").innerHTML=xmlhttp.responseText;
            }
            };
            xmlhttp.open( "GET","DealServlet3?testStr=" +str,true);
            xmlhttp.send();
      }
</script>
</head>
<body>
 
       <h3> 请在下面的输入框中键入字母(A - H): </h3>
       <form action="" >
            姓氏: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
       </form>
       <p> 建议:<span id="txtHint"></ span></p >
 
</body>
</html>
而处理请求的DealServlet3代码为:
package com.servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet(name="DealServlet3" ,urlPatterns="/DealServlet3")
public class DealServlet3 extends HttpServlet {
       private static final long serialVersionUID = 1L;
   
       protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
            
            String str = request .getParameter("testStr");
            PrintWriter out = response .getWriter();
            String[] names = {"Ami","Bob" ,"Cal" ,"Davi" ,"Ella" ,"Fill" ,"Gates" ,"Hebe" };
            
            String temp=null ;
             if(str .length()==1&&str.charAt(0)>= 'A'&&str .charAt(0)<='H'){
                   for(int i =0;i<names.length;i++){
                         if(names [i ].charAt(0)==str.charAt(0)){
                               temp=names [i ];
                               break;
                        }
                  }
                   if(temp ==null){
                         out.write("no suggestion" );
                  } else{
                         out.write(temp );
                  }
            } else{
                   out.write("no suggestion" );
            }     
      }
}
该实例的执行过程分析:
当用户在上面的输入框输入字符时,会执行函数showHint( ),该函数由onkeyup事件触发:
   如果输入框为空,则str.length==0则该函数清空txtHint占位符的内容,退出函数。
  如果输入框不为空,showHint( )函数会执行:
      1)创建XMLHttpRequest对象
     2)当服务器就绪时执行函数
     3)把请求发送到服务器上的文件进行处理
原文地址:https://www.cnblogs.com/zwbg/p/5902862.html