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

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


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

与使用GET的例子相比,通过HTTP的POST请求发送数据并没有更多的困难。

首先,改变对open()方法的调用方式,现在使用POST参数:

xhr.open("POST",url,true);

其次,如果要发送任何数据到服务器上,需要确保设置报头(header)来表示使用的编码类型。在大多数情况下,这将是Web浏览器进行表单提交所使用的标准的x-www-form-urlencoded格式:

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

一个常见的错误是省略了这个报头,所以当通过POST传输数据时,总是要使用合适的编码值来添加报头。

其次,必须注册一个回调函数,但是当使用send()方法来初始化请求时,把负载数据作为参数传递到方法中:

xhr.send("rating=5");

实例

通过POST发送数据。

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)对象通过POST发送数据-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("POST",url,true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    xhr.onreadystatechange = function(){handleResponse(xhr);};
    xhr.send(payload);
  }
}
function handleResponse(xhr)
{
  if (xhr.readyState == 4  && xhr.status == 200)
  {
    var responseOutput = document.getElementById("responseOutput");
    responseOutput.innerHTML = xhr.responseText;
  }
}
function rate(rating, comment)
{
  /* determine rating value */
  var ratingVal = 0;
  for (var i=0; i < rating.length; i++)
  {
    if (rating[i].checked)
    {
      ratingVal = rating[i].value;
      break;
    }
  }
  var url = "http://www.baike369.com/baike369.php";
  var payload = "rating=" + encodeValue(ratingVal) + "&comment=" + encodeValue(comment);
  sendRequest(url, payload);
  /* kill form submission */
  return false;
}
window.onload = function () 
{ 
  document.ratingForm.onsubmit = function () { return rate(this.rating,this.comment.value); };
};
</script> 
</head>
<body>
<h3>How do you feel about Ajax?</h3>
<form action="#" name="ratingForm" method="post" >
<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 />
<label>Comments:<br />
<textarea id="comment" name="comment" rows="5" cols="40"></textarea></label><br />
<input type="submit" value="vote" />
</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)对象通过POST发送数据


提示

尽管几乎所有的POST请求都会设置成使用application/x-www-form-urlencoded的内容编码,但仍可以设置任何期望的编码方法。

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