完整AJAX实例 实现一个简单的 GET 请求

创建 XMLHttpRequest 对象

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

 

创建 XMLHttpRequest 对象的语法:

variable=new XMLHttpRequest();

 

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:

variable=new ActiveXObject("Microsoft.XMLHTTP");

 

为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :

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");
  }

------摘自http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_create.asp------

 


 

向服务器发送请求

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

xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();

GET 请求

一个简单的 GET 请求:

xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();

在上面的例子中,您可能得到的是缓存的结果。

为了避免这种情况,请向 URL 添加一个唯一的 ID:

xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();

--------摘自http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_send.asp-------

 


 

【下面是自己做的一个练习】

 

 javascript放在body里了(小懒...):

<body>
<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","demo_get.asp?t=" + Math.random(),true);
//xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
}
</script>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>

 

demo_get.asp代码:

<%
response.Write("<p style='color:red'>本内容是使用 GET 方法请求</p>")
response.Write("<p style='color:blue'>请求时间  " & now() & "</p>")
%>

 

运行结果:

    

posted @ 2014-01-24 16:32  fjenny_贞  阅读(1164)  评论(0编辑  收藏  举报