www.baike369.com
百科369 > Ajax教程 > XMLHttpRequest(XHR)对象通过GET发送数据

XMLHttpRequest(XHR)对象通过GET发送数据


XMLHttpRequest(XHR)对象通过GET发送数据

XMLHttpRequest(XHR)对象可以通过HTTP的GET请求发送数据,这种方式把数据添加到一个在URL中的查询字符串中发送出去。当然,在使用基于XHR通信的情况下,同样的做法也是可以的,所做的工作只是创建XHR对象,并且使用追加的查询字符串把它设置为请求所期望的URL:

var xhr = createXHR();
if (xhr){
  xhr.open("GET", "http://www.baike369.com/baike369.php?rating=5", true);
  xhr.onreadystatechange = function(){handleResponse(xhr);};
  xhr.send(null);
}

从上面的代码可以看出,创建一个请求非常简单,但是仍然需要遵循编程规范,并且还要保证负载URL的安全,同样也要认识到,使用这样的方法来传递的数据在数量上是有限制的。


实例

本例通过GET发送数据。

1. 创建ratings.txt文件,输入一些字符。比如:

www.baike369.com

2. 创建totals.txt文本文件。

3. 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)对象通过GET发送数据-www.baike369.com</title>
<script type="text/javascript">
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();
	if(xhr)
	{
		xhr.open("GET",url+"?"+payload,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 = xhr.responseText;
    }
}
function rate(rating)
{
	var url="http://www.baike369.com/baike369.php";
	var payload="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><br /><br />
</form>
<br />
<div id="responseOutput">&nbsp;</div>
</body>
</html>

4. baike369.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;
}
?>

5. 显示效果如下:

XMLHttpRequest(XHR)对象通过GET发送数据

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