您当前的位置:首页 > 网站建设 > ajax
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery |

Ajax异步加载解析

51自学网 2022-02-21 10:53:12
  ajax

AJAX (Asynchronous JavaScript and XML,异步的 JavaScript 和 XML)。它不是新的编程语言,而是一种使用现有标准的新方法,是在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的艺术。
那么,让我们一起走进AJax的世界吧。

基础语法

学习Ajax之前,我们要明确自己的需求,那就是在不刷新页面的前提下实现异步的与服务器进行交互,更新页面信息。使用Ajax其实也是很简单的,我们只需要遵循一定的步骤即可。
 •创建Ajax对象(原生的需要判断当前浏览器的类型)
 •设置回调函数 (完成与服务器的交互之后所触发的函数)
 •打开请求,并发送。(根据请求方式的不同,代码书写稍有不同)
 •客户端获得反馈数据,更新页面 

获取Ajax对象

不同的浏览器对Ajax的支持是不一致的,所以我们要区别的对待。

设置回调函数

设置回调函数的目的就是在Ajax完成与服务器的交互之后,将获取到的数据信息,添加到页面上。

通常我们会指定onreadystatechange函数作为我们的回调处理函数。

相关于Ajax与服务器交互有如下状态信息供我们在编码的过程找中参考。

.readystate

关于加载状态有如下几个常用的数值:
 •0: 请求未初始化
 •1: 服务器连接已建立
 •2: 请求已接收
 •3: 请求处理中
 •4: 请求已完成,且响应已就绪 

.status

加载结果的状态信息有:
 •200: “OK”

 •404: “未找到此页面”

 开启交互

一谈起交互,映入脑海的就是双方。也就是我们的ajax客户端和服务器之间的交互。所以我们需要明确请求数据在服务器上的位置

open(method,url,async) 

url的使用会根据method的不同而不同,这一点我们务必要清楚。至于asynchronous这个参数,一般来说对于数据量很小的请求可以采用false,但是建议使用true来进行异步的加载,来避免服务器压力过大。

•GET方式

只是用这种方式很简单,指定url在服务器上的位置即可。这里红色部分的理解相当的重要。我们务必指定url为请求在服务器上的位置,一般采用绝对路径的方式。

// 对Servlet来说指定其注解上的位置即可xmlhttp.open("GET","/Test/servlet/AjaxServlet?userinput="+str.value,true);  xmlhttp.send();

 •POST方式

使用POST方式的时候,我们需要额外的多一项处理。如下例:

xmlhttp.open("POST","ajax_test.asp",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");// 在send方法中指定要传输的参数信息即可xmlhttp.send("fname=Bill&lname=Gates");

客户端更新页面

对于Ajax来说,顾名思义。是采用xml形式来传输数据的。但是目前而言,这不再是唯一的一种形式了。那么我们怎么将获取到的数据更新到网页上呢?有如下两种方式。
 •如果来自服务器的响应并非 XML,请使用 responseText 属性。
 document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

•如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML属性:

xmlDoc=xmlhttp.responseXML;txt="";x=xmlDoc.getElementsByTagName("ARTIST");for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; }document.getElementById("myDiv").innerHTML=txt;

实例体验

了解了这些基础语法之后,我们就可以在实际的开发中简单的应用了。为了更好的完成此次实验,我先做了一个简单的JavaWeb,来处理我们的Ajax请求。

使用Servlet方式

AjaxServlet.java

package one;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;/** * Servlet implementation class AjaxServlet */@WebServlet("/AjaxServlet")public class AjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; /**  * @see HttpServlet#HttpServlet()  */ public AjaxServlet() {  super();  // TODO Auto-generated constructor stub } /**  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse  *  response)  */ protected void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  // TODO Auto-generated method stub  //response.getWriter().append("Served at: ").append(request.getContextPath());  String userinput = request.getParameter("userinput");  System.out.println("客户端连接!");  System.out.println("请求信息为:" + userinput);  PrintWriter out = response.getWriter();  if(userinput.equals("") || userinput.length()<6) {   response.setContentType("text/html;charset=UTF-8");   response.setCharacterEncoding("UTF-8");   response.setHeader("Content-Type", "text/html;charset=utf-8");   out.write("<h3>the length of input string must be more than 6!</h3>");  }else{   response.setContentType("text/html;charset=UTF-8");   response.setCharacterEncoding("UTF-8");   response.setHeader("Content-Type", "text/html;charset=utf-8");   out.println("<h3>Correct!</h3>");  }  out.close(); } /**  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse  *  response)  */ protected void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  // TODO Auto-generated method stub  doGet(request, response); }}

 web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>AjaxServlet</servlet-name> <servlet-class>one.AjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServlet</servlet-name> <url-pattern>/servlet/AjaxServlet</url-pattern> </servlet-mapping></web-app>

ajax.html

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Ajax测试</title></head><body><div> <h2>AJAX Test</h2> <input type="text" name="userinput" placeholder="用户输入,Ajax方式获得数据" onblur="getResult(this)"> <br> <span id="ajax_result"></span> <script> getResult = function(str){  var httpxml;  if(0 == str.value.length) {   document.getElementById("ajax_result").innerHTML = "Nothing";   }   if (window.XMLHttpRequest) {   xmlhttp = new XMLHttpRequest();  }else{   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  }  xmlhttp.onreadystatechange = function(){   if(4 == xmlhttp.readyState && 200 == xmlhttp.status) {    document.getElementById("ajax_result").innerHTML = xmlhttp.responseText;   }  }  xmlhttp.open("GET","/Test/servlet/AjaxServlet?userinput="+str.value,true);  xmlhttp.send();  } </script></div></body></html>

实验结果
 •长度小于6时:

•长度大于等于6:

使用JSP方式

receiveParams.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%   //接收参数   String userinput = request.getParameter("userinput");   //控制台输出表单数据看看   System.out.println("userinput =" + userinput);   //检查code的合法性   if (userinput == null || userinput.trim().length() == 0) {     out.println("code can't be null or empty");   } else if (userinput != null && userinput.equals("admin")) {     out.println("code can't be admin");   } else {     out.println("OK");  } %>

ajax.html

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Ajax测试</title></head><body><div> <h2>AJAX Test</h2> <input type="text" name="userinput" placeholder="用户输入,Ajax方式获得数据" onblur="getResult(this)"> <br> <span id="ajax_result"></span> <script> getResult = function(str){  var httpxml;  if(0 == str.value.length) {   document.getElementById("ajax_result").innerHTML = "Nothing";   }   if (window.XMLHttpRequest) {   xmlhttp = new XMLHttpRequest();  }else{   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  }  xmlhttp.onreadystatechange = function(){   if(4 == xmlhttp.readyState && 200 == xmlhttp.status) {    document.getElementById("ajax_result").innerHTML = xmlhttp.responseText;   }  }  //xmlhttp.open("GET","/Test/servlet/AjaxServlet?userinput="+str.value,true);  xmlhttp.open("GET","receiveParams.jsp?userinput="+str.value,true);  xmlhttp.send();  } </script></div></body></html>

效果一致。

JQuery 中的Ajax

前面介绍的是原生的Ajax实现方式,我们需要做的工作还是很多的,而JQuery帮助我们完成了平台无关性的工作,我们只需要专注于业务逻辑的开发即可。直接用jquery的.post或者.get或者.ajax方法,更方便更简单,js代码如下:
 •.POST方式

 $.post("./newProject",{newProjectName:project_name},   function(data,status){  //alert("data:" + data + "status:" + status);  if(status == "success"){   var nodes = data.getElementsByTagName("project");   //alert(nodes[0].getAttribute("name"));   for(var i = 0;i < nodes.length;i ++){    $("#project_items").append("<option value=/"" + (i+1) + "/">" + nodes[i].getAttribute("name") + "</option>");    }  } })

•.ajax方式

 $(function(){  //按钮单击时执行  $("#testAjax").click(function(){    //Ajax调用处理   $.ajax({    type: "POST",    url: "test.php",    data: "name=garfield&age=18",    success: function(data){      $("#myDiv").html('<h2>'+data+'</h2>');     }   });   }); });

 •.get方式

 $(document).ready(function(){ $("#bt").click(function(){ $.get("mytest/demo/antzone.txt",function(data,status){  alert("Data:"+data+"/nStatus:"+status); }) })})

总结

今天的演示对于实际开发的过程中,服务器端的用户输入数据验证,或者即时更新页面而又减少网络流量是非常的有必要的。而且用处也很广泛,还能有效的提升用户体验。

这次的案例,就当是抛砖引玉,给你的应用也添加上异步加载吧。


下载地址:
Ajax技术组成与核心原理分析
ajax同步验证单号是否存在的方法
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1