js建立XMLHttpRequest对象及其属性和方法

 
  1. //定义变量,存储对象   
  2. var xmlHttp;   
  3. //创建XMLHttpRequest对象   
  4. function creatXMLHttpRequest()   
  5. {   
  6.     if(window.ActiveXObject)   
  7.     {   
  8.         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");   
  9.     }   
  10.     else if(window.XMLHttpRequest)   
  11.     {   
  12.         xmlHttp=new XMLHttpRequest();   
  13.     }   
  14. }   
  15. //使用get方式建立与后台的交互   
  16. function callServer()   
  17. {   
  18.     creatXMLHttpRequest()   
  19.     var email=document.getElementById("TxtEmail").value;   
  20.     if(email=="")   
  21.     {   
  22.         document.getElementById("LabMsg").innerText="请输入邮箱!";   
  23.         document.getElementById("LabMsg").style.color="red";   
  24.     }   
  25.     else  
  26.     {   
  27.         url="register.aspx?email=" + email + "&ts" + new Date().getTime();   
  28.         xmlHttp.onreadystatechange=handleStateChange;   
  29.         xmlHttp.open("GET",url,true);   
  30.         xmlHttp.send(null);   
  31.     }   
  32. }   
  33. //回调函数,后台处理完结果后返回给回调函数   
  34. function handleStateChange()   
  35. {   
  36.     //请求的状态有5个值:0=未初始化;1=正在加载;2=已经加载;3=交互中;4=完成;  
  37.     if(xmlHttp.readyState==4)   
  38.     {   
  39.         //200对应OK,如404=未找到网页   
  40.         if(xmlHttp.status==200)   
  41.         {   
  42.             var result=xmlHttp.responseXML.getElementsByTagName("result")[0].firstChild.nodeValue;   
  43.             if(result=="true")   
  44.             {   
  45.                 document.getElementById("LabMsg").innerHTML="恭喜,可用!";   
  46.                 document.getElementById("LabMsg").style.color="red";   
  47.             }   
  48.             else if(result=="false")   
  49.             {   
  50.                 document.getElementById("LabMsg").innerText="该邮箱已存在!";   
  51.                 document.getElementById("LabMsg").style.color="red";   
  52.             }   
  53.         }   
  54.     }   
  55. }   
  56.   
  57. post请求   
  58.     url="register.aspx?email=" + email + "&ts" + new Date().getTime();   
  59.    xmlHttp.onreadystatechange=handleStateChange;   
  60.    xmlHttp.open("POST",url,false);              
  61.    xmlHttp.SetRequestHeader("Content-Type","application/x-www-form-urlencoded");              
  62.    xmlHttp.send(null);  
    

 

后台处理请求的代码:

  1. //写在所请求的URL页面的page_load下   
  2.         string email;    
  3.         email = Request.QueryString["email"];   
  4.         myCustomer.Email = email;   
  5.         if (email == string.Empty || email == null)   
  6.         {   
  7.             return;   
  8.         }   
  9.         else  
  10.         {   
  11.             StringBuilder result = new StringBuilder("<result>");   
  12.             if (myCheck.HaveCustomer(myCustomer))   
  13.             {   
  14.   
  15.                 result.Append("false");   
  16.                 result.Append("</result>");   
  17.                 Response.ContentType = "text/xml";   
  18.                 Response.Write(result.ToString());   
  19.                 Response.End();   
  20.             }   
  21.             else  
  22.             {   
  23.                 result.Append("true");   
  24.                 result.Append("</result>");   
  25.                 Response.ContentType = "text/xml";   
  26.                 Response.Write(result.ToString());   
  27.                 Response.End();   
  28.             }   
  29.         }  

 

XMLHttpRequest对象的属性

     XMLHttpRequest对象提供了许多属性,处理XMLHttpRequest时需要频繁用到这些属性,如下表所示:

 

 

属性

描述

onreadystatechange

每个状态改变时都会触发这个事件处理程序,通常会调用一个JavaScript函数

readyState

请求的状态

responseText

服务器的响应,表示为一个串

responseXML

服务器的响应,表示为XML,这个对象可以解析为一个DOM对象

status

服务器的HTTP状态

statusText

HTTP状态的对应文本

 

下面是属性和事件的详细说明

 

1. readyState属性

  当XMLHttpRequest对象吧一个HTTP请求发送到服务器时将经历若干种状态。一直等待直到请求被处理,然后,它才接收一个响应。这样以来,脚本才正确响应各种状态,XMLHttpRequest对象暴露一个描述对象的当前状态的readyState属性,如下表所示:

 

readyState取值

描述

0

描述一种“未初始化”状态。此时,已经创建了一个XMLHttpRequest对象,但是还没有初始化。

1

描述一种“发送”状态。此时,代码已经调用了XMLHttpRequest open()方法并且XMLHttpRequest已经准备好把一个请求发送到服务器。

2

描述一种“发送”状态。此时,已经通过send()方法把一个请求发送到服务器端,但是还没有收到一个响应。

3

描述一种“正在接收”状态。此时,已经接收到HTTP响应头部信息,但是消息体部分还没有完全接收结束。

4

描述一种“已加载”状态。此时,响应已经被完全接收。

 

 

2. onreadystatechange属性

   无论readyState值何时发生改变,XMLHttpRequest对象都会激发一个readystatechange事件。其中,onreadystatechange属性接收一个EventListener值,向该方法指示无论readyState值何时发生改变,该对象都将激活。

3. responseText属性

   这个responseText属性包含客户端接收到的HTTP响应的文本内容。当readyState值为0、1或2时,responseText包含一个空字符串。当readyState值为3(正在接收)时,响应中包含客户端还未完成的响应信息。当readyState为4(已加载)时,该responseText包含完整的响应信息。

4. responseXML属性

   此属性用于当接收到完整的HTTP响应时(readyState为4)描述XML响应;此时,Content-Type头部指定MIME(媒体)类型为text/xml,application/xml或以+xml结尾。如果Content-Type头部并不包含这些媒体类型之一,那么responseXML的值为null。无论何时,只要readyState值不为4,那么该responseXML的值也为null。

其实,这个responseXML属性值是一个文档接口类型的对象,用来描述被分析的文档。如果文档不能被分析(例如,如果文档不是良构的或不支持文档相应的字符编码),那么responseXML的值将为null。

5. status属性

   这个属性描述了HTTP状态代码,而且其类型为short。而且,仅当readyState值为3(正在接收中)或4(已加载)时,这个status属性才可用。当readyState的值小于3时试图存取status的值将引发一个异常。例如:status等于200表示成功,404表示未找到资源。

 

状态码:描述  
100:Continue
101:Switching protocols
200:OK
201:Created
202:Accepted
203:Non-Authoritative Information
204:No Content
205:Reset Content
206:Partial Content
300:Multiple Choices
301:Moved Permanently
302:Found
303:See Other
304:Not Modified
305:Use Proxy
307:Temporary Redirect
400:Bad Request
401:Unauthorized
402:Payment Required
403:Forbidden
404:Not Found
405:Method Not Allowed
406:Not Acceptable
407:Proxy Authentication Required
408:Request Timeout
409:Conflict
410:Gone
411:Length Required
412:Precondition Failed
413:Request Entity Too Large

414:Request-URI Too Long
415:Unsupported Media Type 
416:Requested Range Not Suitable 
417:Expectation Failed 
500:Internal Server Error 
501:Not Implemented
502:Bad Gateway
503:Service Unavailable
504:Gateway Timeout 
505:HTTP Version Not Supported

6. statusText属性

   这个属性描述了HTTP状态代码文本,并且仅当readyState值为3或4才可用。当readyState为其它值时试图存取statusText属性将引发一个异常。

 

 

XMLHttpRequest对象的方法

 

   下表显示了XMLHttpRequest对象的一些常用的方法,其中描述部分介绍了这些方法的作用和意义。

 

方法

描述

abort()

停止当前请求

getAllResponseHeaders()

把HTTP请求的所有相应首部作为键/值对返回。

getResponseHeader("header")

返回指定首部的串值。

open("method","url")

建立对服务器的调用。method参数可以是GET、POST或PUT等;url参数可以是相对URL或绝对URL。这个方法还包括3个可选参数。

send(content)

向服务器发送请求。

setRequestHeader("header","value")

把指定首部设置为所提供的值,在设置任何首部之前必须先调用open()方法。

 

 

 

方法:open
创建一个新的http请求,并指定此请求的方法、URL以及验证信息
语法:oXMLHttpRequest.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);
参数
bstrMethod
http方法,例如:POST、GET、PUT及PROPFIND。大小写不敏感。 
bstrUrl
请求的URL地址,可以为绝对地址也可以为相对地址。 
varAsync[可选]
布尔型,指定此请求是否为异步方式,默认为true。如果为真,当状态改变时会调用onreadystatechange属性指定的回调函数。 
bstrUser[可选]
如果服务器需要验证,此处指定用户名,如果未指定,当服务器需要验证时,会弹出验证窗口。 
bstrPassword[可选]
验证信息中的密码部分,如果用户名为空,则此值将被忽略。

备注:调用此方法后,可以调用send方法向服务器发送数据。
xmlhttp.Open("get", "http://localhost/example.htm", false);

方法:send
发送请求到http服务器并接收回应
语法:xmlhttp.send(varBody);
参数:varBody (欲通过此请求发送的数据。) 
备注:此方法的同步或异步方式取决于open方法中的bAsync参数,如果bAsync == False,此方法将会等待请求完成或者超时时才会返回,如果bAsync == True,此方法将立即返回。 
如果发送的数据为BSTR,则回应被编码为utf-8, 必须在适当位置设置一个包含charset的文档类型头。 
如果发送的数据为XML DOM object,则回应将被编码为在xml文档中声明的编码,如果在xml文档中没有声明编码,则使用默认的UTF-8。 
xmlhttp.Send(xmldoc);

方法:getAllResponseHeaders
获取响应的所有http头
语法:strValue = xmlhttp.getAllResponseHeaders();
备注:每个http头名称和值用冒号分割,并以rn结束。当send方法完成后才可调用该方法。 
alert(xmlhttp.getAllResponseHeaders());

 

方法:getResponseHeader
从响应信息中获取指定的http头
语法:strValue = xmlhttp.getResponseHeader(bstrHeader);
备注:当send方法成功后才可调用该方法。如果服务器返回的文档类型为"text/xml", 则这句话
xmlhttp.getResponseHeader("Content-Type");将返回字符串"text/xml"。可以使用getAllResponseHeaders方法获取完整的http头信息。 
alert(xmlhttp.getResponseHeader("Content-Type")); // 输出http头中的Content-Type列:当前web服务器的版本及名称。

 

方法:abort
取消当前请求
语法:xmlhttp.abort();
备注:调用此方法后,当前请求返回UNINITIALIZED 状态。

 

方法:setRequestHeader
单独指定请求的某个http头
语法:xmlhttp.setRequestHeader(bstrHeader, bstrValue);
参数:bstrHeader(字符串,头名称。) bstrValue(字符串,值。) 
备注:如果已经存在已此名称命名的http头,则覆盖之。此方法必须在open方法后调用。
xmlhttp.setRequestHeader(bstrHeader, bstrValue);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值