Ajax技术(2)--比较完整的原始ajax写法

来源:互联网 发布:淘宝店铺介绍优势范文 编辑:程序博客网 时间:2024/04/28 02:23

转载地址:http://abstractforever.iteye.com/blog/524148

刚开始学习Ajax,当然是先把原理性的东西弄懂了,在去用什么js框架,那样才能得心应手:

以下是我收集的资料,写的注释比较多,适合快速理解和上手使用,因为大部分是js代码,就没有专门写成js文件。

originalityAjax.html代码如下:

Html代码  收藏代码
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  2. <html>  
  3.   <head>  
  4.     <title>最原始的ajax写法</title>  
  5.       
  6.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  7.     <meta http-equiv="description" content="this is my page">  
  8.     <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  9.       
  10.     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  
  11.     <script type="text/javascript">  
  12.       
  13.     //这个方法将使用XMLHTTPRequest对象来进行AJAX的异步数据交互  
  14.     var xmlHttpRequest;  
  15.   
  16.     //用户名校验的方法  
  17.     function verify() {  
  18.         var success = createXMLHTTPRequest();  
  19.         if (!success) {  
  20.             return;  
  21.         }  
  22.         var userName = document.getElementById("userName").value;//获取用户名字  
  23.         //2.注册回调函数  
  24.         //注册回调函数时,之需要函数名,不要加括号  
  25.         //我们需要将函数名注册,如果加上括号,就会把函数的返回值注册上,这是错误的  
  26.         xmlHttpRequest.onreadystatechange = callback;  
  27.   
  28.         //3。设置连接信息  
  29.         //第一个参数表示http的请求方式,支持所有http的请求方式,主要使用get和post  
  30.         //第二个参数表示请求的url地址,get方式请求的参数也在url中  
  31.         //第三个参数表示采用异步还是同步方式交互,true表示异步  
  32.         //记住在url后面加上时间戳  
  33.         //xmlHttpRequest.open("GET", "OriginalityAjaxAction?username=" + userName, true);  
  34.   
  35.         //POST方式请求的代码  
  36.         xmlHttpRequest.open("POST", "OriginalityAjaxAction", true);  
  37.         //POST方式需要自己设置http的请求头  
  38.         xmlHttpRequest.setRequestHeader("Content-Type",  
  39.                 "application/x-www-form-urlencoded");  
  40.         //POST方式发送数据  
  41.         xmlHttpRequest.send("username=" + userName);  
  42.   
  43.         //4.发送数据,开始和服务器端进行交互  
  44.         //同步方式下,send这句话会在服务器段数据回来后才执行完  
  45.         //异步方式下,send这句话会立即完成执行  
  46.         //xmlHttpRequest.send(null);  
  47.   
  48.     }  
  49.   
  50.     //回调函数  
  51.     function callback() {  
  52.         //alert(xmlHttpRequest.readyState);  
  53.         //5。接收响应数据  
  54.         //判断对象的状态是交互完成  
  55.         if (xmlHttpRequest.readyState == 4) {  
  56.             //判断http的交互是否成功  
  57.             if (xmlHttpRequest.status == 200) {  
  58.                 //获取服务器器端返回的数据  
  59.                 //获取服务器段输出的纯文本数据  
  60.                 var responseText = xmlHttpRequest.responseText;  
  61.                 //将数据显示在页面上  
  62.                 //通过dom的方式找到div标签所对应的元素节点  
  63.                 var divNode = document.getElementById("result");  
  64.                 //设置元素节点中的html内容  
  65.                 divNode.innerHTML = responseText;  
  66.             } else {  
  67.                 alert("出错了!!!");  
  68.             }  
  69.         }  
  70.     }  
  71.   
  72.     //创建XMLHTTPRequest对象来进行AJAX的异步数据交互  
  73.     function createXMLHTTPRequest() {  
  74.         //1.创建XMLHttpRequest对象  
  75.         //这是XMLHttpReuquest对象无部使用中最复杂的一步  
  76.         //需要针对IE和其他类型的浏览器建立这个对象的不同方式写不同的代码  
  77.   
  78.         if (window.XMLHttpRequest) {  
  79.             //针对FireFox,Mozillar,Opera,Safari,IE7,IE8  
  80.             xmlHttpRequest = new XMLHttpRequest();  
  81.             //针对某些特定版本的mozillar浏览器的BUG进行修正  
  82.             if (xmlHttpRequest.overrideMimeType) {  
  83.                 xmlHttpRequest.overrideMimeType("text/xml");  
  84.             }  
  85.         } else if (window.ActiveXObject) {  
  86.             //针对IE6,IE5.5,IE5  
  87.             //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个js的数组中  
  88.             //排在前面的版本较新  
  89.             var activexName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];  
  90.             for ( var i = 0; i < activexName.length; i++) {  
  91.                 try {  
  92.                     //取出一个控件名进行创建,如果创建成功就终止循环  
  93.                     //如果创建失败,回抛出异常,然后可以继续循环,继续尝试创建  
  94.                     xmlHttpRequest = new ActiveXObject(activexName[i]);  
  95.                     break;  
  96.                 } catch (e) {  
  97.                 }  
  98.             }  
  99.         }  
  100.         //确认XMLHTtpRequest对象是否创建成功  
  101.         if (!xmlHttpRequest) {  
  102.             alert("XMLHttpRequest对象创建失败!!");  
  103.             return false;  
  104.         } else {  
  105.             //0 - 本地响应成功  
  106.             //alert(xmlhttp.readyState);  
  107.             return true;  
  108.         }  
  109.     }  
  110. </script>  
  111.   </head>  
  112.     
  113.   <body>  
  114.         请输入要验证的用户名字(输入admin试试):<br/>  
  115.         <input type="text" id="username"/><input type="button" value="校验" onclick="verify()"/>  
  116.         <div id="result"></div>  
  117.   </body>  
  118. </html>  

 和servlet交互的,OriginalityAjaxAction.java代码如下:

Java代码  收藏代码
  1. package web.action;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  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. //对原始的ajax页面请求的控制器  
  10. public class OriginalityAjaxAction extends HttpServlet {  
  11.   
  12.     private static final long serialVersionUID = 1978049925174268801L;  
  13.   
  14.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  15.             throws ServletException, IOException {  
  16.   
  17.         this.doPost(request, response);  
  18.     }  
  19.   
  20.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  21.             throws ServletException, IOException {  
  22.         request.setCharacterEncoding("UTF-8");  
  23.           
  24.         String username = request.getParameter("username");  
  25.         response.setCharacterEncoding("UTF-8");  
  26.         PrintWriter out = response.getWriter();  
  27.         //将数据返回给页面  
  28.         if(username.equals("admin")){  
  29.             out.print("用户:[admin]已经被使用了");  
  30.         }else{  
  31.             out.print("用户:[" + username + "]可以使用");  
  32.         }  
  33.     }  
  34.   
  35. }  

 web.xml的servlet配置如下:

Xml代码  收藏代码
  1. <servlet>  
  2.     <servlet-name>OriginalityAjaxAction</servlet-name>  
  3.     <servlet-class>web.action.OriginalityAjaxAction</servlet-class>  
  4.   </servlet>  
  5.   
  6.   <servlet-mapping>  
  7.     <servlet-name>OriginalityAjaxAction</servlet-name>  
  8.     <url-pattern>/OriginalityAjaxAction</url-pattern>  
  9.   </servlet-mapping>  

 以上简单的页面和servlet交互,返回一个字符串结果。

下面进行扩展,解析servlet返回的xml数据,为了保证代码的完整性,下面列出完整代码:

originalityAjaxXml.html

Html代码  收藏代码
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  2. <html>  
  3.   <head>  
  4.     <title>最原始的ajax解析xml数据写法</title>  
  5.       
  6.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  7.     <meta http-equiv="description" content="this is my page">  
  8.     <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  9.       
  10.     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  
  11.     <script type="text/javascript">  
  12.       
  13.     //这个方法将使用XMLHTTPRequest对象来进行AJAX的异步数据交互  
  14.     var xmlHttpRequest;  
  15.   
  16.     //读取后台xml数据的方法  
  17.     function readxml() {  
  18.         var success = createXMLHTTPRequest();  
  19.         if (!success) {  
  20.             return;  
  21.         }  
  22.           
  23.         //2.注册回调函数  
  24.         //注册回调函数时,之需要函数名,不要加括号  
  25.         //我们需要将函数名注册,如果加上括号,就会把函数的返回值注册上,这是错误的  
  26.         xmlHttpRequest.onreadystatechange = callback;  
  27.   
  28.         //3。设置连接信息  
  29.         //第一个参数表示http的请求方式,支持所有http的请求方式,主要使用get和post  
  30.         //第二个参数表示请求的url地址,get方式请求的参数也在url中  
  31.         //第三个参数表示采用异步还是同步方式交互,true表示异步  
  32.   
  33.   
  34.         //POST方式请求的代码  
  35.         xmlHttpRequest.open("POST", "OriginalityAjaxXmlAction", true);  
  36.         //POST方式需要自己设置http的请求头  
  37.         xmlHttpRequest.setRequestHeader("Content-Type",  
  38.                 "application/x-www-form-urlencoded");  
  39.         //POST方式发送数据  
  40.           
  41.   
  42.         //4.发送数据,开始和服务器端进行交互  
  43.         //同步方式下,send这句话会在服务器段数据回来后才执行完  
  44.         //异步方式下,send这句话会立即完成执行  
  45.         xmlHttpRequest.send(null);  
  46.   
  47.     }  
  48.   
  49.     //回调函数  
  50.     function callback() {  
  51.         //5。接收响应数据  
  52.         //判断对象的状态是交互完成  
  53.         if (xmlHttpRequest.readyState == 4) {  
  54.             //判断http的交互是否成功  
  55.             if (xmlHttpRequest.status == 200) {  
  56.                 //获取服务器器端返回的数据  
  57.                 //获取服务器段输出的纯文本数据  
  58.                 var rootNode = xmlHttpRequest.responseXML;;  
  59.                 //利用getElementsByTagName可以根据标签名来获取元素节点,返回的是一个数组  
  60.                 var productNodes = rootNode.getElementsByTagName("product");  
  61.                   
  62.                 //将获取到的内容解析成表格显示  
  63.                 for(var i=0;i<productNodes.length;i++){//创建行数  
  64.                     var product = document.createElement("TR");  
  65.                     //每行8的td标签  
  66.                     var name = document.createElement("TD");  
  67.                     name.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("name")[0].firstChild.nodeValue));//给name赋值  
  68.                     var description = document.createElement("TD");  
  69.                     description.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("description")[0].firstChild.nodeValue));  
  70.                     var price = document.createElement("TD");  
  71.                     price.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("price")[0].firstChild.nodeValue));  
  72.                     var image = document.createElement("TD");  
  73.                     image.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("image")[0].firstChild.nodeValue));  
  74.                     var series = document.createElement("TD");  
  75.                     series.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("series")[0].firstChild.nodeValue));  
  76.                     var triband = document.createElement("TD");  
  77.                     triband.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("triband")[0].firstChild.nodeValue));  
  78.                     var camera = document.createElement("TD");  
  79.                     camera.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("camera")[0].firstChild.nodeValue));  
  80.                     var video = document.createElement("TD");  
  81.                     video.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("video")[0].firstChild.nodeValue));  
  82.                     //将所有的td依附到tr上去  
  83.                     product.appendChild(name);  
  84.                     product.appendChild(description);  
  85.                     product.appendChild(price);  
  86.                     product.appendChild(image);  
  87.                     product.appendChild(series);  
  88.                     product.appendChild(triband);  
  89.                     product.appendChild(camera);  
  90.                     product.appendChild(video);  
  91.                     document.getElementById("productBody").appendChild(product);   
  92.                       
  93.                 }  
  94.             } else {  
  95.                 alert("出错了!!!");  
  96.             }  
  97.         }  
  98.     }  
  99.   
  100.     //创建XMLHTTPRequest对象来进行AJAX的异步数据交互  
  101.     function createXMLHTTPRequest() {  
  102.         //1.创建XMLHttpRequest对象  
  103.         //这是XMLHttpReuquest对象无部使用中最复杂的一步  
  104.         //需要针对IE和其他类型的浏览器建立这个对象的不同方式写不同的代码  
  105.   
  106.         if (window.XMLHttpRequest) {  
  107.             //针对FireFox,Mozillar,Opera,Safari,IE7,IE8  
  108.             xmlHttpRequest = new XMLHttpRequest();  
  109.             //针对某些特定版本的mozillar浏览器的BUG进行修正  
  110.             if (xmlHttpRequest.overrideMimeType) {  
  111.                 xmlHttpRequest.overrideMimeType("text/xml");  
  112.             }  
  113.         } else if (window.ActiveXObject) {  
  114.             //针对IE6,IE5.5,IE5  
  115.             //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个js的数组中  
  116.             //排在前面的版本较新  
  117.             var activexName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];  
  118.             for ( var i = 0; i < activexName.length; i++) {  
  119.                 try {  
  120.                     //取出一个控件名进行创建,如果创建成功就终止循环  
  121.                     //如果创建失败,回抛出异常,然后可以继续循环,继续尝试创建  
  122.                     xmlHttpRequest = new ActiveXObject(activexName[i]);  
  123.                     break;  
  124.                 } catch (e) {  
  125.                 }  
  126.             }  
  127.         }  
  128.           
  129.         //确认XMLHTtpRequest对象是否创建成功  
  130.         if (!xmlHttpRequest) {  
  131.             alert("XMLHttpRequest对象创建失败!!");  
  132.             return false;  
  133.         } else {  
  134.             //0 - 本地响应成功  
  135.             //alert(xmlhttp.readyState);  
  136.             return true;  
  137.         }  
  138.     }  
  139.       
  140. </script>  
  141.   
  142.   </head>  
  143.     
  144.   <body>  
  145.         读取服务器的xml数据:  
  146.         <input type="button" value="读取" onClick="readxml()"/><br/>  
  147.         解析xml数据为表格的形式:<br/>  
  148.         <table border="1" id="productTable">  
  149.             <tbody id="productBody">  
  150.             <tr>  
  151.                 <td>name</td>  
  152.                 <td>description</td>  
  153.                 <td>price</td>  
  154.                 <td>image</td>  
  155.                 <td>series</td>  
  156.                 <td>triband</td>  
  157.                 <td>camera</td>  
  158.                 <td>video</td>  
  159.             </tr>  
  160.             </tbody>  
  161.         </table>  
  162.           
  163.           
  164.           
  165.   </body>  
  166. </html>  

 后台的catalog.xml数据代码:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <catalog>  
  3.   
  4.     <product productId="1">  
  5.         <name>Nokia 6010中文的哈</name>  
  6.         <description>Easy to use without sacrificing style, the Nokia 6010 phone offers functional voice communication supported by text messaging, multimedia messaging, mobile internet, games and more</description>  
  7.         <price>99.99</price>  
  8.         <image>Nokia_6010.gif</image>  
  9.         <series>6000</series>  
  10.         <triband>false</triband>  
  11.         <camera>false</camera>  
  12.         <video>false</video>  
  13.         <highlight1>MMS</highlight1>  
  14.         <highlight2>Large color display</highlight2>  
  15.         <qtyInStock>2</qtyInStock>  
  16.     </product>  
  17.   
  18.     <product productId="2">  
  19.         <name>Nokia 3100 Blue</name>  
  20.         <description>Light up the night with a glow-in-the-dark cover - when it's charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-onâ„¢ gaming cover*, you'll get luminescent light effects in time to the gaming action.</description>  
  21.         <price>139</price>  
  22.         <image>Nokia_3100_blue.gif</image>  
  23.         <series>3000</series>  
  24.         <triband>true</triband>  
  25.         <camera>false</camera>  
  26.         <video>false</video>  
  27.         <highlight1>Glow-in-the-dark</highlight1>  
  28.         <highlight2>Flashing lights</highlight2>  
  29.         <qtyInStock>1</qtyInStock>  
  30.     </product>  
  31.   
  32.     <product productId="3">  
  33.         <name>Nokia 3100 Pink</name>  
  34.         <description>Light up the night with a glow-in-the-dark cover - when it's charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-onâ„¢ gaming cover*, you'll get luminescent light effects in time to the gaming action.</description>  
  35.         <price>139</price>  
  36.         <image>Nokia_3100_pink.gif</image>  
  37.         <series>3000</series>  
  38.         <triband>true</triband>  
  39.         <camera>false</camera>  
  40.         <video>false</video>  
  41.         <highlight1>Glow-in-the-dark</highlight1>  
  42.         <highlight2>Flashing lights</highlight2>  
  43.         <qtyInStock>7</qtyInStock>  
  44.     </product>  
  45.   
  46.     <product productId="4">  
  47.         <name>Nokia 3120</name>  
  48.         <description>Designed for both business and pleasure, the elegant Nokia 3120 phone offers a pleasing mix of features. Enclosed within its chic, compact body, you will discover the benefits of tri-band compatibility, a color screen, MMS, XHTML browsing, cheerful screensavers, and much more.</description>  
  49.         <price>159.99</price>  
  50.         <image>Nokia_3120.gif</image>  
  51.         <series>3000</series>  
  52.         <triband>true</triband>  
  53.         <camera>false</camera>  
  54.         <video>false</video>  
  55.         <highlight1>Multimedia messaging</highlight1>  
  56.         <highlight2>Animated screensavers</highlight2>  
  57.         <qtyInStock>15</qtyInStock>  
  58.     </product>  
  59.   
  60.     <product productId="5">  
  61.         <name>Nokia 3220</name>  
  62.         <description>The Nokia 3220 phone is a fresh new cut on some familiar ideas - animate your MMS messages with cute characters, see the music with lights that flash in time with your ringing tone, download wallpapers and screensavers with matching color schemes for the interface.</description>  
  63.         <price>159.99</price>  
  64.         <image>Nokia_3220.gif</image>  
  65.         <series>3000</series>  
  66.         <triband>false</triband>  
  67.         <camera>true</camera>  
  68.         <video>false</video>  
  69.         <highlight1>MIDI tones</highlight1>  
  70.         <highlight2>Cut-out covers</highlight2>  
  71.         <qtyInStock>5</qtyInStock>  
  72.     </product>  
  73.   
  74. </catalog>  

 

OriginalityAjaxXmlAction.java代码如下:

Java代码  收藏代码
  1. package web.action;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.dom4j.Document;  
  12. import org.dom4j.DocumentException;  
  13. import org.dom4j.io.SAXReader;  
  14. //对原始的ajax页面请求的控制器  
  15. //返回xml格式的数据  
  16. public class OriginalityAjaxXmlAction extends HttpServlet {  
  17.   
  18.     private static final long serialVersionUID = 1978049925174268801L;  
  19.   
  20.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  21.             throws ServletException, IOException {  
  22.   
  23.         this.doPost(request, response);  
  24.     }  
  25.   
  26.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  27.             throws ServletException, IOException {  
  28.         request.setCharacterEncoding("UTF-8");  
  29.         response.setContentType("text/xml;charset=utf-8");  
  30.         response.setHeader("Cache-Control""no-cache");  
  31.         String path  = request.getSession().getServletContext().getRealPath("/") + "catalog.xml";  
  32.         PrintWriter out = response.getWriter();  
  33.           
  34.          SAXReader saxReader = new SAXReader();   
  35.          Document document = null;  
  36.         try {  
  37.             document = saxReader.read(new File(path));  
  38.         } catch (DocumentException e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.            
  42.          String xml = document.asXML();  
  43.          System.out.println(xml);  
  44.          out.print(xml);  
  45.     }  
  46.   
  47. }  

 完整例子代码下载:ajaxDemo.rar (750.3 KB)


1 0
原创粉丝点击