XMLHttpRequest对象

来源:互联网 发布:淘宝商城女装新款时尚 编辑:程序博客网 时间:2024/05/16 11:28

<span style="font-family: KaiTi_GB2312; background-color: rgb(255, 255, 255);">最近在学习AJAX这块内容的时候对XMLHttpRequest理解不是很到位,故留下一篇博客,整理自己的思路。</span>

1.什么是 XMLHttpRequest 对象?

XMLHttpRequest对象用于在后台与服务器交换数据。

XMLHttpRequest对象是开发者的梦想,因为您能够:

  • 在不重新加载页面的情况下更新网页
  • 在页面已加载后从服务器请求数据
  • 在页面已加载后从服务器接收数据
  • 在后台向服务器发送数据

所有现代的浏览器都支持 XMLHttpRequest 对象。

2.小实例

3.代码展示

<!DOCTYPE html><!--To change this license header, choose License Headers in Project Properties.To change this template file, choose Tools | Templatesand open the template in the editor.--><html><head><script type="text/javascript">var xmlhttp;function loadXMLDoc(url){xmlhttp=null;if (window.XMLHttpRequest)  {// code for IE7, Firefox, Opera, etc.      //创建xmlhttprequest对象  xmlhttp=new XMLHttpRequest();  }else if (window.ActiveXObject)  {// code for IE6, IE5(老版的IE56浏览器用ActiveXObject创建)  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }if (xmlhttp!=null)  {      //onreadystatechange是一个事件句柄。他的值state_Change是一个函数的名字。当状态发生变化的时候      //会触发此函数  xmlhttp.onreadystatechange=state_Change;  //para true规定请求是否异步处理  xmlhttp.open("GET",url,true);  //send方法执行之后,脚本继续执行,不等待来自服务器的响应。  xmlhttp.send(null);  }else  {  alert("您的浏览器不支持httpRequest.");  }}function state_Change(){    //仅当状态为4时候,我们才执行代码if (xmlhttp.readyState==4)  {// 4 = "loaded"  if (xmlhttp.status==200)    {// 200 = "OK"    document.getElementById('A1').innerHTML=xmlhttp.status;    document.getElementById('A2').innerHTML=xmlhttp.statusText;    document.getElementById('A3').innerHTML=xmlhttp.responseText;    }  else    {    alert("Problem retrieving XML data:" + xmlhttp.statusText);    }  }}</script></head><body><h2>Using the HttpRequest Object</h2><p><b>state:</b><span id="A1"></span></p><p><b>state text:</b><span id="A2"></span></p><p><b>response:</b><br /><span id="A3"></span></p><button onclick="loadXMLDoc('/example/xdom/note.xml')">get XML</button></body></html>

0 0
原创粉丝点击