Ajax-XMLHttpRequest对象 - 我的天地

Ajax-XMLHttpRequest对象

rurutia posted @ 2007年3月31日 22:05 in web开发 with tags ajax web , 2477 阅读

买了本ajax的 书,看了一下,对核心之一的XMLHttpRequest对象有了大致的了解,使用起来还是挺简 单的:

首先,创建对象:


  1. var xmlHttp;
  2. function createXMLHttpRequest(){
  3.         if(window.ActiveXObject){
  4.                 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  5.         }else if (window.XMLHttpRequest){
  6.                 xmlHttp = new XMLHttpRequest();
  7.         }
  8. }

因为要照顾IE的缘故,需要这个判断,xmlHttp就是创建 好的对象,之后的事情基本都靠它完成。

之后自然是发送请求,设置回调 函数:

  1. GET方法:
  2. xmlHttp.open("GET",url,ture);
  3. xmlHttp.onreadystatechange = callback;
  4. xmlHttp.send(null);
  5.  
  6. POST方法:
  7. xmlHttp.open("POST",url,ture);
  8. xmlHttp.onreadystatechange = callback;
  9. xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
  10. xmlHttp.send(something);

在回调函数 里,判断服务器是否成功应答了请求一般是下面的方法:


  1. if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
  2.         {
  3.                 ………………
  4.         }

得到返回数据的方法有两种,一种 是文本,一种是xml对象:


  1. 文本:
  2. xmlHttp.responseText
  3.  
  4. xml对象:
  5. xmlHttp.responseXML

返回的xml对象就可以直接依照DOM访 问了,真方便。总之就这么简单,最大的优点就是异步,可以在后台悄悄的干事情(嘿 嘿~),剩下的就要自己发挥了~

 



登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee