head rush ajax chapter5 POST
/**
每个浏览器都有URL最大长度限制,长度2000以内都可以接受,而GET请求将数据放在请求的URL中,如果URL太长,就会被删掉多余的部分,导致请求失败。POST请求送出的数据和URL是分开的,一旦服务器取得一个POST请求,会先搞清楚所收到的数据是什么类型,然后将这个数据传给URL所要求的程序。浏览器不会试图缓存POST请求。在一个GET请求中,数据是请求URL的一部分,所以一定是文本。但是在POST请求中,你可以送出图像或XML或纯文本,所以你必须告诉服务器数据是什么类型的,以方便服务器对数据解码并用适当的方式处理,使用request.setRequestHeader()。将关于请求的消息告诉服务器,可以使用请求标头。POST请求并不比GET安全多少,指示多了一个解码数据的过程,很容易就可以获取。SQL注入:将电话栏输入' || 'a' = 'a,而在服务器段的sql语句为:select * from breakneck where phone='phone',如果把上句带入phone中 where phone='' || 'a'='a' 这条语句总是为true会导致所有数据都被选择。可以在表单中对输入的数据进行验证。保护永远不嫌多。黑客可以直接向服务器送出请求,而不经过web页面。
*/
pizza.js
function getCustomerInfo() {
var phone = document.getElementById("phone").value;
if(validatePhone(phone)==false) return; //验证输入的是一个电话号码
var url = "lookupCustomer.php?phone=" +
escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
/* Get the response from the server */
var customerAddress = request.responseText;
/* Update the HTML web form */
document.getElementById("address").value =
customerAddress;
} else
alert("Error! Request status is " + request.status);
}
}
function submitOrder() {
var phone = document.getElementById("phone").value;//获取相关元素数据
var address = document.getElementById("address").value;
var order = document.getElementById("order").value;
var url = "placeOrder.php";//请求的URL地址
request.open("POST", url, true);//建立请求连接
request.onreadystatechange = showConfirmation;
//Content-Type是请求标头的名字,后面是它的值
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
//使用名/值对,发送数据,用&隔开
request.send("phone=" + escape(phone) +
"&address=" + escape(address) +
"&order=" + escape(order));
}
function showConfirmation() {//显示确认信息同时取代html中的form的位置
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText;
// Locate form on page
var mainDiv = document.getElementById("main-page");//获得表单的父元素
var orderForm = document.getElementById("order-form");//获得表单元素
// Create some confirmation text
pElement = document.createElement("p");//创建一个新的元素
textNode = document.createTextNode("Your order should arrive within " +
response + " minutes. Enjoy your pizza!");
pElement.appendChild(textNode);
// Replace the form with the confirmation
mainDiv.replaceChild(pElement, orderForm);
} else {
var message = request.getResponseHeader("Status");
if ((message == null) || (message.length <= 0)) {
alert("Error! Request status is " + request.status);
} else {
alert(message);
}
}
}
}
placeOder.php
<?php
include("order.php");
include("delivery.php");
// Error checking
$order = $_REQUEST['order'];//用来取得请求数据
$address = $_REQUEST['address'];
if (strlen($order) <= 0) {//确保订单内容不是一个空字符串
header("Status: No order was received.", true, 400);//400指示有错误发生
echo " ";//有些浏览器一定要取得来自服务器的响应,否则会出现"undefined",送出一个空响应
exit;
}
if (strlen($address) <= 0) {
header("Status: No address was received.", true, 400);
//Status是响应标头,后面的一切都是他的值,true表示如果有同名标头就取而代之,送出400状态码
//任何时候,只要服务器响应你的请求,就可以用响应标头给你响应本身的信息,JavaScript可以通过请求对象访问响应标头 request.getResponseHeader("Status")
echo " ";
exit;
}
// Place the order
$pizzaOrder = new PizzaOrder($order, $address);
$pizzaOrder->cookOrder();
$pizzaOrder->prepOrder();
// Deliver the order
$delivery = new Delivery($pizzaOrder);
$delivery->deliver();
$deliveryTime = $delivery->getDeliveryEstimate();
echo $deliveryTime;
?>
validation.js
/**
* DHTML phone number validation script.
* Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/
// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function checkInternationalPhone(strPhone) {
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}
function validatePhone(phoneNumber) {
if ((phoneNumber == null) || (phoneNumber == "")) {
alert("Please enter your phone number.");
return false;
}
if (checkInternationalPhone(phoneNumber) == false) {
alert("Please enter a valid phone number.");
return false;
}
return true;
}
lookup_mysql.php
<?php
/////////////////////
//
// This script assumes MySQL access.
//
// If you want to run this script yourself,
// you need to do the following things:
// 1. Replace DB_HOST with the name of the server your database is on
// 2. Replace DB_USERNAME with your database login username
// 3. Replace DB_PASSWORD with your database password
// 4. Replace DB_NAME with the name of your MySQL database
// 5. Make sure your database schema is as follows:
//
// Table name: hraj_breakneck
// Column 1: phone (Type: VARCHAR(15))
// Column 2: name (Type: VARCHAR(100))
// Column 3: street1 (Type: VARCHAR(100))
// Column 4: city (Type: VARCHAR(25))
// Column 5: state (Type: VARCHAR(20))
// Column 6: zipCode (Type: VARCHAR(10))
//
// Insert into your table several rows like this to start:
//
// 2148760976, Doug Henderson, 7804 Jumping Hill Lane, Dallas, Texas, 75218
// 2142908762, Mary Jenkins, 7081 Teakwood #24C, Dallas, Texas, 75182
// 7852215645, John Jacobs, 234 East Rutherford Drive, Topeka, Kansas, 66608
// 7853485412, Happy Traum, 876 Links Circle, Topeka, Kansas, 66608
//
// Remember, you really don't need this script to access a database to run
// the book's examples. This is just for bonus credit!
//
///////////////////
// Connect to database
$conn = @mysql_connect("DB_HOST", "DB_USERNAME", "DB_PASSWORD");
if (!$conn)
die("Error connecting to MySQL: " . mysql_error());
if (!mysql_select_db("DB_NAME", $conn))
die("Error selecting database: " . mysql_error());
$phone = preg_replace("/[\. \(\)\-]/", "", $_REQUEST['phone']);
$phone = mysql_real_escape_string($phone); //将字符串中的特殊字符处理掉
$select = 'SELECT *';
$from = ' FROM hraj_breakneck';
$where = ' WHERE phone = \'' . $phone . '\'';
$queryResult = @mysql_query($select . $from . $where);
if (!$queryResult)
die('Error retrieving customer from the database.');
$num = mysql_num_rows($queryResult);
if ($num == 0) {
$queryResult = @mysql_query($select . $from);
}
$row = mysql_fetch_array($queryResult); //只有一个顾客的数据被读取
echo $row['name'] . "\n" .
$row['street1'] . "\n" .
$row['city'] . ", " .
$row['state'] . " " .
$row['zipCode'];
}
mysql_close($conn);
?>
每个浏览器都有URL最大长度限制,长度2000以内都可以接受,而GET请求将数据放在请求的URL中,如果URL太长,就会被删掉多余的部分,导致请求失败。POST请求送出的数据和URL是分开的,一旦服务器取得一个POST请求,会先搞清楚所收到的数据是什么类型,然后将这个数据传给URL所要求的程序。浏览器不会试图缓存POST请求。在一个GET请求中,数据是请求URL的一部分,所以一定是文本。但是在POST请求中,你可以送出图像或XML或纯文本,所以你必须告诉服务器数据是什么类型的,以方便服务器对数据解码并用适当的方式处理,使用request.setRequestHeader()。将关于请求的消息告诉服务器,可以使用请求标头。POST请求并不比GET安全多少,指示多了一个解码数据的过程,很容易就可以获取。SQL注入:将电话栏输入' || 'a' = 'a,而在服务器段的sql语句为:select * from breakneck where phone='phone',如果把上句带入phone中 where phone='' || 'a'='a' 这条语句总是为true会导致所有数据都被选择。可以在表单中对输入的数据进行验证。保护永远不嫌多。黑客可以直接向服务器送出请求,而不经过web页面。
*/
pizza.js
function getCustomerInfo() {
var phone = document.getElementById("phone").value;
if(validatePhone(phone)==false) return; //验证输入的是一个电话号码
var url = "lookupCustomer.php?phone=" +
escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
/* Get the response from the server */
var customerAddress = request.responseText;
/* Update the HTML web form */
document.getElementById("address").value =
customerAddress;
} else
alert("Error! Request status is " + request.status);
}
}
function submitOrder() {
var phone = document.getElementById("phone").value;//获取相关元素数据
var address = document.getElementById("address").value;
var order = document.getElementById("order").value;
var url = "placeOrder.php";//请求的URL地址
request.open("POST", url, true);//建立请求连接
request.onreadystatechange = showConfirmation;
//Content-Type是请求标头的名字,后面是它的值
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
//使用名/值对,发送数据,用&隔开
request.send("phone=" + escape(phone) +
"&address=" + escape(address) +
"&order=" + escape(order));
}
function showConfirmation() {//显示确认信息同时取代html中的form的位置
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText;
// Locate form on page
var mainDiv = document.getElementById("main-page");//获得表单的父元素
var orderForm = document.getElementById("order-form");//获得表单元素
// Create some confirmation text
pElement = document.createElement("p");//创建一个新的元素
textNode = document.createTextNode("Your order should arrive within " +
response + " minutes. Enjoy your pizza!");
pElement.appendChild(textNode);
// Replace the form with the confirmation
mainDiv.replaceChild(pElement, orderForm);
} else {
var message = request.getResponseHeader("Status");
if ((message == null) || (message.length <= 0)) {
alert("Error! Request status is " + request.status);
} else {
alert(message);
}
}
}
}
placeOder.php
<?php
include("order.php");
include("delivery.php");
// Error checking
$order = $_REQUEST['order'];//用来取得请求数据
$address = $_REQUEST['address'];
if (strlen($order) <= 0) {//确保订单内容不是一个空字符串
header("Status: No order was received.", true, 400);//400指示有错误发生
echo " ";//有些浏览器一定要取得来自服务器的响应,否则会出现"undefined",送出一个空响应
exit;
}
if (strlen($address) <= 0) {
header("Status: No address was received.", true, 400);
//Status是响应标头,后面的一切都是他的值,true表示如果有同名标头就取而代之,送出400状态码
//任何时候,只要服务器响应你的请求,就可以用响应标头给你响应本身的信息,JavaScript可以通过请求对象访问响应标头 request.getResponseHeader("Status")
echo " ";
exit;
}
// Place the order
$pizzaOrder = new PizzaOrder($order, $address);
$pizzaOrder->cookOrder();
$pizzaOrder->prepOrder();
// Deliver the order
$delivery = new Delivery($pizzaOrder);
$delivery->deliver();
$deliveryTime = $delivery->getDeliveryEstimate();
echo $deliveryTime;
?>
validation.js
/**
* DHTML phone number validation script.
* Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/
// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function checkInternationalPhone(strPhone) {
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}
function validatePhone(phoneNumber) {
if ((phoneNumber == null) || (phoneNumber == "")) {
alert("Please enter your phone number.");
return false;
}
if (checkInternationalPhone(phoneNumber) == false) {
alert("Please enter a valid phone number.");
return false;
}
return true;
}
lookup_mysql.php
<?php
/////////////////////
//
// This script assumes MySQL access.
//
// If you want to run this script yourself,
// you need to do the following things:
// 1. Replace DB_HOST with the name of the server your database is on
// 2. Replace DB_USERNAME with your database login username
// 3. Replace DB_PASSWORD with your database password
// 4. Replace DB_NAME with the name of your MySQL database
// 5. Make sure your database schema is as follows:
//
// Table name: hraj_breakneck
// Column 1: phone (Type: VARCHAR(15))
// Column 2: name (Type: VARCHAR(100))
// Column 3: street1 (Type: VARCHAR(100))
// Column 4: city (Type: VARCHAR(25))
// Column 5: state (Type: VARCHAR(20))
// Column 6: zipCode (Type: VARCHAR(10))
//
// Insert into your table several rows like this to start:
//
// 2148760976, Doug Henderson, 7804 Jumping Hill Lane, Dallas, Texas, 75218
// 2142908762, Mary Jenkins, 7081 Teakwood #24C, Dallas, Texas, 75182
// 7852215645, John Jacobs, 234 East Rutherford Drive, Topeka, Kansas, 66608
// 7853485412, Happy Traum, 876 Links Circle, Topeka, Kansas, 66608
//
// Remember, you really don't need this script to access a database to run
// the book's examples. This is just for bonus credit!
//
///////////////////
// Connect to database
$conn = @mysql_connect("DB_HOST", "DB_USERNAME", "DB_PASSWORD");
if (!$conn)
die("Error connecting to MySQL: " . mysql_error());
if (!mysql_select_db("DB_NAME", $conn))
die("Error selecting database: " . mysql_error());
$phone = preg_replace("/[\. \(\)\-]/", "", $_REQUEST['phone']);
$phone = mysql_real_escape_string($phone); //将字符串中的特殊字符处理掉
$select = 'SELECT *';
$from = ' FROM hraj_breakneck';
$where = ' WHERE phone = \'' . $phone . '\'';
$queryResult = @mysql_query($select . $from . $where);
if (!$queryResult)
die('Error retrieving customer from the database.');
$num = mysql_num_rows($queryResult);
if ($num == 0) {
$queryResult = @mysql_query($select . $from);
}
$row = mysql_fetch_array($queryResult); //只有一个顾客的数据被读取
echo $row['name'] . "\n" .
$row['street1'] . "\n" .
$row['city'] . ", " .
$row['state'] . " " .
$row['zipCode'];
}
mysql_close($conn);
?>