XMLHttpRequest对象


<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 | Templates
and 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 οnclick="loadXMLDoc('/example/xdom/note.xml')">get XML</button>

</body>
</html>

评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值