Ajax详解

来源:互联网 发布:全球直播软件 编辑:程序博客网 时间:2024/05/20 11:48

:什么是Ajax

Ajax(Asynchronous JavaScript And XML)是异步的JavaScriptxml。也就是异步请求更新技术。Ajax是一种对现有技术的一种新的应用,不是一门新语言。它是用JavaScript编写。与xml的关系就是可以读取和返回xml文件。

:Ajax中的对象和方法说明

Ajax的核心对象就是xmlHttpRequest

XMLHttpRequest用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

   1:方法

xmlHttpRequst对象利用send()open()方法与服务器进行交互。

open(method,url,async)

  • method:请求的类型;GET  POST
  • url:文件在服务器上的位置
  • asynctrue(异步)或 false(同步)

send(string)

  • string:仅用于 POST 请求

如果是post请求,必须使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中设置发送的数据:

[javascript] view plaincopy
  1. xmlhttp.open("POST","ajax_test.asp",true);  
  2. xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");  
  3. xmlhttp.send("fname=Bill&lname=Gates");  

:属性

readyState

  • 0: 请求未初始化
  • 1: 服务器连接已建立
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已就绪

State

  • 200: "OK"
  • 404: 未找到页面

responseText

  • 获得字符串形式的响应数据。

responseXML

  • 获得 XML 形式的响应数据。

onreadystatechange

  • 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

:Ajax运行原理(为什么要用Ajax)



ajax通过xmlhttpRequest对象执行操作,其中xmlhttpRequest对象是在浏览器中内置的一个对象

其运行原理就相当于创建了一个请求代理,通过代理去完成与服务器的交互,交互的过程中客户不需要等待,还可以进行其它的工作,交互完成以后,代理再将交互的结果返回给客户页面。

第一步:创建xmlHttpRequest对象,每个浏览器的创建不是都相同。

[javascript] view plaincopy
  1. var xmlhttp;  
  2. if (window.XMLHttpRequest)  
  3.   {//  IE7+, Firefox, Chrome, Opera, Safari创建方式  
  4.   xmlhttp=new XMLHttpRequest();  
  5.   }  
  6. else  
  7.   {//  IE6, IE5 创建方式  
  8.   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  
  9.   
  10.   }  

通常情况下为了兼容所有浏览器,每个都要写上。

第二步:设置open()方法和setRequestHeader()方法参数。

将请求方式,请求目的地址,和请求类型设置到open方法中,如果是post请求,则需要设置setRequestHeader()参数

第三步:发送执行

利用send方法,与服务器真正的交互执行

第四步:获得执行结果

首先判断执行是否完成,然后通过js操作dom元素,将返回的responseText返回到页面

[javascript] view plaincopy
  1. xmlhttp.onreadystatechange=function()  
  2.   {  
  3.     //判断是否发送成功,是否找到请求页面等  
  4.   if (xmlhttp.readyState==4 && xmlhttp.status==200)  
  5.     {  
  6.     //操作页面元素  
  7.     document.getElementById("myDiv").innerHTML=xmlhttp.responseText;  
  8.     }  
  9.   }  

:Ajax实例(焦点离开验证用户是否存在)

利用ajax在焦点离开的时候判断注册的用户是否存在

[javascript] view plaincopy
  1. var xmlHttp;//声明xmlHttp对象  
  2. //实例化xmlHttpRequest对象  
  3. function createXMLHttpRequest() {  
  4.     //表示当前浏览器不是ie,如ns,firefox  
  5.     if(window.XMLHttpRequest) {  
  6.         xmlHttp = new XMLHttpRequest();  
  7.     } else if (window.ActiveXObject) {  
  8.         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
  9.     }  
  10. }  
  11. //input失去焦点事件onblur(),调用这个js方法验证  
  12. function validate(field) {  
  13.     if (trim(field.value).length != 0) {  
  14.         //创建XMLHttpRequest  
  15.         createXMLHttpRequest();  
  16.         //每次请求的url地址不同,利用时间产生不同url地址,可以防止缓冲造成问题  
  17.         var url = "user_validate.jsp?userId=" + trim(field.value) + "×tamp=" + new Date().getTime();  
  18.         xmlHttp.open("GET", url, true);  
  19.         //方法地址,处理完成后自动调用,回调  
  20.         xmlHttp.onreadystatechange=function() { //匿名函数  
  21.             if(xmlHttp.readyState == 4) { //Ajax引擎初始化成功  
  22.                 if (xmlHttp.status == 200) { //http协议成功  
  23.                     document.getElementById("userIdSpan").innerHTML = "<font color='red'>" + xmlHttp.responseText + "</font>";  
  24.                 }else {  
  25.                     alert("请求失败,错误码=" + xmlHttp.status);  
  26.                 }  
  27.             }  
  28.         };  
  29.         //将参数发送到Ajax引擎  
  30.         xmlHttp.send(null);  
  31.     }else {  
  32.         document.getElementById("userIdSpan").innerHTML = "";  
  33.     }  
  34. }  
页面部分代码:

[html] view plaincopy
  1. <td width="78%">  
  2.     <input name="userId" type="text" class="text1" id="userId"  
  3.         size="10" maxlength="10" onkeypress="userIdOnKeyPress()" value="<%=userId %>" onblur="validate(this)"><span id="userIdSpan"></span>  
  4. </td>  


//后台验证方法利用jsp编写

[java] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=GB18030"  
  2.     pageEncoding="GB18030"%>  
  3. <%@ page import="com.bjpowernode.drp.sysmgr.manager.*" %>      
  4. <%     
  5.   
  6.     //可以采用清除缓存的方法,如下  
  7.     //response.setContentType("text/xml");  
  8.     //response.setHeader("Cache-Control", "no-store"); //HTTP1.1      
  9.     //response.setHeader("Pragma", "no-cache"); //HTTP1.0  
  10.     //response.setDateHeader("Expires", 0);   
  11.   
  12.     //out.println("Hello");  
  13.     //Thread.currentThread().sleep(3000);  
  14.     String userId = request.getParameter("userId");  
  15.     if (UserManager.getInstance().findUserById(userId) != null) {  
  16.         out.println("用户代码已经存在");  
  17.     }  
  18.   
  19. %  

原创粉丝点击