AJAX——XMLHttpRequest

来源:互联网 发布:mac itunes铃声制作 编辑:程序博客网 时间:2024/05/22 05:20

XMLHttpRequest是AJAX的基础。


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


一、创建XMLHttpRequest对象:

所有的现代浏览器(IE7+、FireFox、Chrome、Safari以及Opera)均內建XMLHttpRequest对象。


创建XMLHttpRequest对象的语法:

var = new XMLHttpRequest();

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:
variable=new ActiveXObject("Microsoft.XMLHTTP");

为了应对现在所有的浏览器,我们在创建XMLHttpRequest对象时需要进行判断,如果支持,则创建XMlHttpRequest对象,如果不支持,则创建ActiveXObject :

var xmlhttp;

if(window.XMLHttpRequest){

// for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp =  new XMLHttpRequest();

} else {

// for IE6, IE5

xmlhttp = new ActiveXObject('Microsoft.XMLHTTP");

}


二、AJAX——向服务器发送请求

如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:

xmlhttp.open(method , url , async );

参数规定了请求的类型,URL以及是否异步处理请求。method请求类型有:GET或POST;url 文件在服务上的位置;async :true(异步) 或 false(同步 )

eg:

<span style="white-space:pre"></span>xmlhttp.open("GET","test1.txt",true);

xmlhttp.send(string) 是将请求发送到服务器; string :仅用于POST请求。

(1). 一个简单的Get请求

<span style="white-space:pre"></span>xmlhttp.open("GET","test.jsp",true);<span style="white-space:pre"></span>xmlhttp.send();
(2). 

在上面的例子中,您可能得到的是缓存的结果。
为了避免这种情况,请向 URL 添加一个唯一的 ID:

xmlhttp.open("GET","test.jsp?t="+Math.random(),true);<span></span>xmlhttp.send();

(3).如果使用GET方法发送,则:

<span style="white-space:pre"></span>xmlhttp.open("GET","test.jsp?fname=mm&lname=hh",true);<span></span>xmlhttp.send();

(4).POST 请求

<span style="white-space:pre"></span>xmlhttp.open("POST","test.jsp",true);<span></span>xmlhttp.send();

(5)如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:


setRequestHeader(header , value) 向请求添加HTTP头。 参数: header : 规定头的名称  ; value: 规定头的值

<span></span>xmlhttp.open("POST","ajax_test.asp",true);<span></span>xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");<span></span>xmlhttp.send("fname=Bill&lname=Gates");<span></span>

 (6). url——服务器上的文件

open()方法的url参数是服务器上文件的地址:

xmlhttp.open('Get' , 'test.jsp  , true')

(7). 异步——True 或 False 

AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML)。
XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true

xmlhttp.open('Get' , 'test.jsp  , true')

通过 AJAX,JavaScript 无需等待服务器的响应,而是:
*在等待服务器响应时执行其他脚本
*当响应就绪后对响应进行处理

(8). Async = true
当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:

<span style="white-space:pre"></span>xmlhttp.onreadystatechange=function()<span style="white-space:pre"></span>  {<span style="white-space:pre"></span>  if (xmlhttp.readyState==4 && xmlhttp.status==200)<span style="white-space:pre"></span>    {<span style="white-space:pre"></span>    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;<span style="white-space:pre"></span>    }<span style="white-space:pre"></span>  }<span style="white-space:pre"></span>xmlhttp.open("GET","test1.txt",true);<span style="white-space:pre"></span>xmlhttp.send();
(9).  Async = false

xmlhttp.open('Get' , 'test.jsp  ,false)

当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:

<span style="white-space:pre"></span>xmlhttp.open("GET","test1.txt",false);<span style="white-space:pre"></span>xmlhttp.send();<span style="white-space:pre"></span>document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

三、AJAX——服务器响应

通过XMLHttpRequest对象的responseText 或 responseXML属性来获取服务器的响应:

responseText : 获得字符串形式的响应数据

responseXML:获得XML形式的响应数据

(1). responseText 属性:

来自服务器端的响应并非 XML,使用responseText 属性;

eg:  

<span style="white-space:pre"></span>document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
<span style="white-space:pre"></span>实例:
<span style="white-space:pre"></span><pre name="code" class="html"><html><head><script type="text/javascript">function loadXMLDoc(){var xmlhttp;if (window.XMLHttpRequest)  {// code for IE7+, Firefox, Chrome, Opera, Safari  xmlhttp=new XMLHttpRequest();  }else  {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }xmlhttp.onreadystatechange=function()  {  if (xmlhttp.readyState==4 && xmlhttp.status==200)    {    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;    }  }xmlhttp.open("GET","/ajax/test1.txt",true);xmlhttp.send();}</script></head><body><div id="myDiv"><h2>Let AJAX change this text</h2></div><button type="button" onclick="loadXMLDoc()">通过 AJAX 改变内容</button></body></html>

(2). responseXML 属性:

来自服务器的响应是XML,需要作为XML对象进行解析时使用responseXML属性:

test.xml

<!--   Copyright w3school.com.cn  --><!--  W3School.com.cn bookstore example  --><bookstore><book category="children"><title lang="en">Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price></book><book category="cooking"><title lang="en">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book><book category="web" cover="paperback"><title lang="en">Learning XML</title><author>Erik T. Ray</author><year>2003</year><price>39.95</price></book><book category="web"><title lang="en">XQuery Kick Start</title><author>James McGovern</author><author>Per Bothner</author><author>Kurt Cagle</author><author>James Linn</author><author>Vaidyanathan Nagarajan</author><year>2003</year><price>49.99</price></book></bookstore>

请求XML文件并解析响应:

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;

四、AJAX——onreadystatechange 事件

(1). 当请求被发送到服务器时,需要执行一些基于响应的任务。每当readyState改变时,就会触发onreadystatechange事件。readState属性存有XMLHttpRequest的状态信息。

关于XMLHttpRequest 对象的三个重要的属性:

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

存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

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

200: "OK"

404: 未找到页面

在onreadystatechange事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。

在readyState等于e且状态等于200时,表示响应已就绪:
xmlhttp.onreadystatechange = function() {

if( xmlhttp.readyState == 4 && xmlhttp.status = 200 ) {

document.getElementById('myDiv').innerHTML = xmlhttp.responseText;

}

}

(2).  使用callback函数

callback函数是一种以参数形式传递给另一个函数的函数。

如果存在多个AJAX任务时,应该为创建XMLHttpRequest对象编写一个标准的函数,并为每个AJAX任务调用该函数:

该函数调用应该包含URL以及发生的onreadystatechange事件时执行的任务 (每次调用可能不尽相同):

function myFunction(){

loadXMLDoc(' test.txt '  ,function() {

if(XMLhttp.readyState == 4 && xmlhttp.status ==  200){

document.getElementById( 'myDiv' ).innerHTML = xmlhttp.responseText;

}

});

}


0 0
原创粉丝点击