您好,欢迎访问一九零五行业门户网

Ajax异步加载解析实例分享

本文主要为大家详细介绍了ajax 异步加载,什么是ajax 异步加载,如何实现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(myp).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(myp).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> <p>  <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> </p> </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> <p>  <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> </p> </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){       $(#myp).html('<h2>'+data+'</h2>');      }    });    });  });
•.get方式
$(document).ready(function(){  $(#bt).click(function(){  $.get(mytest/demo/antzone.txt,function(data,status){   alert(data:+data+\nstatus:+status);  })  }) })
总结
今天的演示对于实际开发的过程中,服务器端的用户输入数据验证,或者即时更新页面而又减少网络流量是非常的有必要的。而且用处也很广泛,还能有效的提升用户体验。
这次的案例,就当是抛砖引玉,给你的应用也添加上异步加载吧。
相关推荐:
javascript vue.js表格分页,ajax异步加载数据
javascript - ajax异步加载,事件触发问题
php如果抓取ajax异步加载的内容
以上就是ajax异步加载解析实例分享的详细内容。
其它类似信息

推荐信息