www.baike369.com
百科369 > Ajax教程 > XMLHttpRequest(XHR)对象的异步请求(open()方法)

XMLHttpRequest(XHR)对象的异步请求(open()方法)


XMLHttpRequest(XHR)对象的异步请求(open()方法)

异步请求是将open()方法中的异步参数设置为true:

xhr.open("GET", "http://www.baike369.com/baike369.php", true);

实例

本例可以完成一个异步请求。

1. test.html文件的源代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>XMLHttpRequest(XHR)对象的异步请求(open()方法)-www.baike369.com</title>
<script type="text/javascript">
function createXHR()
{
  try { return new XMLHttpRequest(); } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
  return null;
}
function sendRequest()
{
  var xhr = createXHR();
  if (xhr)
  {
    xhr.open("GET", "http://www.baike369.com/baike369.php", true);
    xhr.onreadystatechange = function(){handleResponse(xhr);};
    xhr.send(null);
  }
}
function handleResponse(xhr)
{
  if (xhr.readyState == 4  && xhr.status == 200)
  {
    var responseOutput = document.getElementById("responseOutput");
    responseOutput.innerHTML = "<h3>请求内容:</h3>" + xhr.responseText;
    responseOutput.style.display = "";
  }
}
window.onload = function () 
{ 
  document.requestForm.requestButton.onclick = function () { sendRequest(); };
};
</script> 
</head>
<body>
<form action="#" name="requestForm">
  <input type="button" name="requestButton" value="发送异步请求" />
</form>
<br />
<div id="responseOutput" style="display:none;">&nbsp;</div>
</body>
</html>

2. baike369.php的源代码如下:

<?php
header("Cache-Control:no-cache");
header("Pragma:no-cache");
$ip=GetHostByName($_SERVER['REMOTE_ADDR']);
echo "$ip ".date("h:i:s A");
?>

3. 显示效果如下:

XMLHttpRequest(XHR)对象的异步请求(open()方法)

使用异步请求时,必须要保持创建的连接路径按照及时的方式返回并且没有发生错误。

Copyright© 2011-2016 www.baike369.com All Rights Reserved