www.baike369.com
百科369 > Ajax教程 > XMLHttpRequest(XHR)对象控制请求(abort()方法)

XMLHttpRequest(XHR)对象控制请求(abort()方法)


XMLHttpRequest(XHR)对象控制请求(abort()方法)

一旦发送的请求超越了XMLHttpRequest对象abort()方法的管理能力,XMLHttpRequest对象就只具有相对有限的请求控制力。这一方法提供了浏览器“停止”按钮的基本功能,并且将很有可能用在我们的Ajax应用程序中解决网络超时的问题。


实例

1. 创建ratings.txt和totals.txt文本文件。

2. 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)对象控制请求(abort()方法)实例-www.baike369.com</title>
<script type="text/javascript"> 
var g_abort, timeoutID;
function encodeValue(val)
{
  var encodedVal;
  if (!encodeURIComponent)
  {
    encodedVal = escape(val);
    /* fix the omissions */
    encodedVal = encodedVal.replace(/@/g, '%40');
    encodedVal = encodedVal.replace(/\//g, '%2F');
    encodedVal = encodedVal.replace(/\+/g, '%2B');
  }
  else
  {
    encodedVal = encodeURIComponent(val);
    /* fix the omissions */
    encodedVal = encodedVal.replace(/~/g, '%7E');
    encodedVal = encodedVal.replace(/!/g, '%21');
    encodedVal = encodedVal.replace(/\(/g, '%28');
    encodedVal = encodedVal.replace(/\)/g, '%29');
    encodedVal = encodedVal.replace(/'/g, '%27');
  }
  /* clean up the spaces and return */
  return encodedVal.replace(/\%20/g,'+'); 
}
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(url, payload)
{
  var xhr = createXHR();
  g_abort = false;
  if (xhr)
  {
    xhr.open("GET",url + "?" + payload,true);
    xhr.onreadystatechange = function(){handleResponse(xhr);};
    xhr.send(null);
    timeoutID = window.setTimeout( function() {cancelRequest(xhr);}, 3000);
  }
}
function cancelRequest(xhr)
{
  g_abort = true; //we have to use this variable because after it aborts, the ready state will change to 4.
  xhr.abort();
  var responseOutput = document.getElementById("responseOutput");
  responseOutput.innerHTML = "Sorry, your request timed out.  Please try again later.";
}
function handleResponse(xhr)
{
  if (!g_abort && xhr.readyState == 4  && xhr.status == 200)
  {
    clearTimeout(timeoutID);
    var responseOutput = document.getElementById("responseOutput");
    responseOutput.innerHTML = xhr.responseText;
  }
}
function rate(rating)
{
  var url = "http://www.baike369.com/code.php";
  var payload = "delay=10&rating=" + encodeValue(rating);
  sendRequest(url, payload);
}
window.onload = function () 
{ 
  var radios = document.getElementsByName('rating');
  for (var i = 0; i < radios.length; i++)
  {
    radios[i].onclick = function (){rate(this.value);}; 
  }
};</script> 
</head>
<body>
<h3>How do you feel about Ajax?</h3>
<form action="#" method="get">
<em>Hate It - </em> [
<input type="radio" name="rating" value="1" /> 1
<input type="radio" name="rating" value="2" /> 2
<input type="radio" name="rating" value="3" /> 3
<input type="radio" name="rating" value="4" /> 4
<input type="radio" name="rating" value="5" /> 5
] <em> - Love It</em>
</form>
<br />
<div id="responseOutput">&nbsp;</div>
</body>
</html>

3. code.php文件的源代码如下:

<?php
if (isset($_REQUEST["delay"]) && is_numeric($_REQUEST["delay"]))
  sleep($_REQUEST["delay"]);
/* File to write to */
$theFile = "ratings.txt";
$totalsFile = "totals.txt";
/* pull the user ratings via the query string */
$rating = htmlentities(substr(urldecode(gpc("rating")),0,1024));
$comment = htmlentities(substr(urldecode(gpc("comment")),0,1024));
$response = strtolower(htmlentities(substr(urldecode(gpc("response")),0,1024)));
$error = htmlentities(substr(urldecode(gpc("error")),0,1024));
$callback = htmlentities(substr(urldecode(gpc("callback")),0,1024));
$validdtd = htmlentities(substr(urldecode(gpc("validdtd")),0,1024));
if ($rating == "")
  $rating = 0;
$transport = "XHR";
if ($response == "")
  $response = "html";
/* if error is set, set appropriate header and then return */
if ($error != "")
{
  if ($error == "404")
    header("HTTP/1.1 404 Not Found\n\n");
  else
    header("HTTP/1.1 500 Internal Server Error\n\n");
  exit;
}
/* record the IP address and time */
$userIP =  $_SERVER['REMOTE_ADDR'];
$currentTime = date("M d y h:i:s A");
/* open the file and get the contents */
$filehandle = fopen($theFile, "r");
if ($filehandle)
{
  $data = fread($filehandle, filesize($theFile));
  fclose($filehandle);
}
else
  die('Failed to read file');
/* open the file and write line to the top of the file */    
$filehandle = fopen($theFile, "w+");
if ($filehandle) 
{
  fwrite($filehandle,"$rating\t $transport\t $userIP @ $currentTime\t $comment\n");
  fwrite($filehandle, $data);
  fclose($filehandle);
}
else
  die('Failed to write file');
//get the totals
$votes = $total = $average = 0;
$filehandle = fopen($totalsFile, "r+");
if ($filehandle) 
{
  $line = fgets($filehandle, 4096);
  $tokens = explode("\t", $line);
  if (count($tokens) > 1)
  {
    $votes = $tokens[0] + 1;
    $total = $tokens[1] + $rating;
  }
  fclose($filehandle);
}
else
  die('Failed to read file');
$filehandle = fopen($totalsFile, "w+");
if ($filehandle) 
{
  fwrite($filehandle,"$votes\t$total\n");
  fclose($filehandle);
}
else
  die('Failed to write file');
if ($votes != 0) $average = round(($total/$votes), 2);
// send the right headers
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Ajax-Response-Type: $response");
$message = "";
if ($response == "html")
{
  $message = "Thank you for voting.  You rated this a <strong>$rating</strong>.  There are <strong>$votes</strong> total votes.  The average is <strong>$average</strong>.  You can see the ratings in the <a href='http://www.baike369.com/ratings.txt' target='_blank'>ratings file</a>";
}
else if ($response == "text")
{
  $message = "Thank you for voting.  You rated this a $rating.  There are $votes total votes.  The average is $average.";
} 
else if ($response == "csv")
{
  $message = "$rating,$average,$votes";
}    
else if ($response == "encoded")
{
  $msg = "Thank you for voting.  You rated this a <strong>$rating</strong>.  There are <strong>$votes</strong> total votes.  The average is <strong>$average</strong>.  You can see the ratings in the <a href='http://www.baike369.com/ratings.txt' target='_blank'>ratings file</a>";
  $message = base64_encode($msg);
}
else if ($response == "xml")
{
  header("Content-Type: text/xml");
  $message = 
  "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
  <!DOCTYPE pollresults SYSTEM \"ratings.dtd\">
    <pollresults>
    <rating>$rating</rating>
    <average>$average</average>
    <votes id=\"votes\"";
    if ($validdtd == "false")
      $message .= " name=\"votes\"";
    $message .= ">$votes</votes>
    </pollresults>
  " ;
}
else if ($response == "xmlbad")
{
  header("Content-Type: text/xml");
  $message = 
  "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n
    <pollresults>\r\n
    <rating>$rating</rating>\r\n
    <average>$average\r\n
    <votes>$votes</votes>\r\n
    </pollresults>\r\n
  " ;
}
else if ($response == "json")
{
  require_once('JSON.php');
  $json = new Services_JSON();
  $jsonResponse = new ResponseData();
  $jsonResponse->rating = $rating;
  $jsonResponse->votes = $votes;
  $jsonResponse->average = $average;
  $message = $json->encode($jsonResponse);
}
else if ($response == "javascript")
{
  $message = "
    var responseOutput = document.getElementById(\"responseOutput\");
  responseOutput.innerHTML += 'Thank you for voting.  You rated this a <strong>$rating</strong>.  There are <strong>$votes</strong> total votes.  The average is <strong>$average</strong>.  You can see the ratings in the <a href=\"http://www.baike369.com/ratings.txt\" target=\"_blank\">ratings file</a>';
  ";
}
echo $message;
/* Helper functions */
function gpc($name)
{
  if (isset($_GET[$name]))
    return $_GET[$name];
  else if (isset($_POST[$name]))
    return $_POST[$name];
  else if (isset($_COOKIE[$name]))
    return $_COOKIE[$name];
  else
    return "";
}
class ResponseData
{
  public $average = 0;
  public $rating = 0;
  public $votes = 0;
  public $total = 0;
}
?>

4. 显示效果如下:

XMLHttpRequest(XHR)对象控制请求(abort()方法)实例

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