XMLHttpRequest创建对象、发送请求、接收响应

Ajax工作原理

XMLHttpRequest 对象

Ajax的核心是XMLHttpRequest对象,它是Ajax实现的关键——发送异步请求、接收响应及执行回调都是通过它来完成的。

所有现代浏览器均支持XMLHttpRequest对象(IE5和IE6使用ActiveXObject)。

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

创建XMLHttpRequest对象

var xmlhttp;
if(window.XMLHttpRequest){
    //code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    //code for IE5, IE6
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

XMLHttpRequest请求

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

xmlhttp.open("method","url",true);
xmlhttp.send();

XMLHttpRequest响应

如需获得来自服务器的响应,请使用XMLHttpRequest对象的responseText或responseXML属性。

如果服务器响应的是responseText,则可以直接这样使用:

<html><!DOCTYPE html>
<html>
<head>
<script>
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","/try/ajax/ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div>
<button type="button" onclick="loadXMLDoc()">修改内容</button>

</body>
</html>

如果服务器响应的事responseXML,则需要对XML进行解析方可使用:

<html><!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
var txt,x,i;
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)
    {
    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;
    }
  }
xmlhttp.open("GET","cd_catalog.xml",true);
xmlhttp.send();
}
</script>
</head>

<body>

<h2>My CD Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
 
</body>
</html>

onreadystatechange事件

当请求被发送到服务器时,我们需要执行一些基于响应的任务。每当readyState改变时,就会触发onreadystatechange事件。

readyState属性存有XMLHttpRequest的状态信息。

下面是XMLHttpRequest对象的三个重要的属性:

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

当readyState等于4且状态为200时,表示响应已就绪。

总结XMLHttpRequest对象使用关键点

1、创建XMLHttpRequest

2、设置回调函数(接收响应处理等)

3、open()

4、send()

 

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值