ajax的发展
ajax(Asynchronous Javascript and XML)异步javascrip和XMl.
ajax只是一种web交互方法。在客户端(浏览器)和服务区段之间传输少量的信息。从而为用户提供及时的响应。
在传统的web应用程序中,浏览器本身负责初始化到服务区的请求,并处理来自服务器的响应。而ajax模式不同,他提供了·一个中间层里处理这种通信。ajax引擎实际上只是一个javascript对象或函数,只有当需要从服务器获取信息时才调用它。
服务器方面配置向ajax引擎返回其可用的数据,这些数据可以是纯文本,XML或者需要的任何格式。唯一的要求就是ajax可以处理这些数据。
随着html帧的引入 早期的ajax雏形出现但是没有用到ajax对象,那就是引用帧技术了。
基本就是把连接给其他的帧,不用去打开另外的一个页面。这里最适合的就是服务器与客户端之间的通信(其实一开始对ajax的理解就是不刷新页面就可以局部的改变页面。例如地图)
这里讲引用帧的介绍了 直接贴代码了。
第一个html页面就叫a.html吧
<frameset rows="100%,0" style="border:0px"> <frame name="displayFrame" src="DataEntry.php" noresize="noresize"> </frame> <frame name="hiddenFrame" src="about:blank" noresize="noresize"></frame> </frameset>
用帧来显示两个页面一个提供表格显示与服务端的数据响应(requestCustomerInfo && displayCustomerInfo),另外一个连接服务器。
<!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> <title>Customer Account Information</title> <script type="text/javascript"> //<![CDATA[ function requestCustomerInfo() { var sId = document.getElementById("txtCustomerId").value; top.frames["hiddenFrame"].location = "GetCustomerData.php?id=" + sId; } function displayCustomerInfo(sText) { var divCustomerInfo = document.getElementById("divCustomerInfo"); divCustomerInfo.innerHTML = sText; } //]]> </script> </head> <body> <p>Enter customer ID number to retrieve information:</p> <p>Customer ID: <input type="text" id="txtCustomerId" value="" /></p> <p><input type="button" value="Get Customer Info" onclick="requestCustomerInfo()" /></p> <div id="divCustomerInfo"></div> </body> </html>
这里的代码 top.frames["hiddenFrame"].location="getcustomerdata.php?id="+sId为隐藏帧指派url.
后台php代码:
<!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> <title>Get Customer Data</title> <?php //customer ID $sID = $_GET["id"]; //validation for ID if (is_numeric($sID) { //variable to hold customer info $sInfo = ""; //database information $sDBServer = "your.database.server"; $sDBName = "your_db_name"; $sDBUsername = "your_db_username"; $sDBPassword = "your_db_password"; //create the SQL query string $sQuery = "Select * from Customers where CustomerId=".$sID; //make the database connection $oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword); @mysql_select_db($sDBName) or $sInfo = "Unable to open database"; if ($sInfo == ""){ if($oResult = mysql_query($sQuery) and mysql_num_rows($oResult) > 0) { $aValues = mysql_fetch_array($oResult,MYSQL_ASSOC); $sInfo = $aValues['Name']."<br />".$aValues['Address']."<br />". $aValues['City']."<br />".$aValues['State']."<br />". $aValues['Zip']."<br /><br />Phone: ".$aValues['Phone']."<br />". "<a href=\"mailto:".$aValues['Email']."\">".$aValues['Email']."</a>"; mysql_free_result($oResult); } else { $sInfo = "Customer with ID $sID doesn't exist."; } } mysql_close($oLink); } else { $sInfo = "Invalid customer ID."; } ?> <script type="text/javascript"> //<![CDATA[ window.onload = function () { var divInfoToReturn = document.getElementById("divInfoToReturn");//获取div文本;作为参数传递个同一级的兄弟窗体top.frames["displayFrame"].
top.frames["displayFrame"].displayCustomerInfo(divInfoToReturn.innerHTML);
}; //]]>
</script>
</head>
<body>
<div id="divInfoToReturn"><?php echo $sInfo ?></div>//在这里添加文本。
</body>
</html>
数据库脚本
CREATE TABLE `Customers` ( `CustomerId` int(11) NOT NULL auto_increment, `Name` varchar(255) NOT NULL default '', `Address` varchar(255) NOT NULL default '', `City` varchar(255) NOT NULL default '', `State` varchar(255) NOT NULL default '', `Zip` varchar(25) NOT NULL default '', `Phone` varchar(25) NOT NULL default '', `Email` varchar(255) NOT NULL default '', PRIMARY KEY (`CustomerId`) )
data:
INSERT INTO Customers VALUES (1, 'Michael Smith', '123 Somewhere Road', 'Beverly Hills', 'California', '90210', '(555) 555-1234', 'michael@somewhere.com');
INSERT INTO Customers VALUES (2, 'Matthew Johnson', '1234 Somewhere Else Street', 'Elsewhere', 'Confusion', '00000', '(555) 555-2345', 'johnboy@neato.net');
INSERT INTO Customers VALUES (3, 'Cindy Benjamin', '1313 Mockingbird Lane', 'Somewhere', 'Montana', '00000', '(555) 555-9876', 'cindybean@mcok.net');
INSERT INTO Customers VALUES (4, 'Mary Klein', '10 Highland Avenue', 'Salem', 'Massachusetts', '01970', '(555) 555-4920', 'mary@klein.net');
II:继续说隐藏帧技术:
上面的是get请求,现在我们来看一下post请求方式(比较贴近ajax的页面无需刷新)
主页面基相同:
<frameset rows="100%,0" style="border: 0px"> <frame name="displayFrame" src="DataEntry.php" noresize="noresize" style="border: 0px" /> <frame name="hiddenFrame" src="about:blank" noresize="noresize" style="border: 0px" /> </frameset> //主页面pre //frames['displayFrame']的链接页面 <head> <title>Create New Customer</title> <script type="text/javascript"> //<![CDATA[ function saveResult(sMessage) { var divStatus = document.getElementById("divStatus"); divStatus.innerHTML = "Request completed: " + sMessage; } //]]> </script> </head> <body> <form method="post" action="SaveCustomer.php" target="hiddenFrame">//target指向frames["hiddenFrame"];页面不会跳转。 <p>Enter customer information to be saved:</p> <p>Customer Name: <input type="text" name="txtName" value="" /><br />
php代码
<!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> <title>Save Customer</title> <?php //get information $sName = mysql_real_escape_string($_POST["txtName"]); $sAddress = mysql_real_escape_string($_POST["txtAddress"]); $sCity = mysql_real_escape_string($_POST["txtCity"]); $sState = mysql_real_escape_string($_POST["txtState"]); $sZipCode = mysql_real_escape_string($_POST["txtZipCode"]); $sPhone = mysql_real_escape_string($_POST["txtPhone"]); $sEmail = mysql_real_escape_string($_POST["txtEmail"]); //status message $sStatus = ""; //database information $sDBServer = "your.database.server"; $sDBName = "your_db_name"; $sDBUsername = "your_db_username"; $sDBPassword = "your_db_password"; //create the SQL query string $sSQL = "Insert into Customers(Name,Address,City,State,Zip,Phone,`Email`) ". " values ('$sName','$sAddress','$sCity','$sState', '$sZipCode'". ", '$sPhone', '$sEmail')"; $oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword); @mysql_select_db($sDBName) or $sStatus = "Unable to open database"; if ($sStatus == "") { if(mysql_query($sSQL)) { $sStatus = "Added customer; customer ID is ".mysql_insert_id(); } else { $sStatus = "An error occurred while inserting; customer not saved."; } } mysql_close($oLink); ?> <script type="text/javascript"> //<![CDATA[ window.onload = function () { top.frames["displayFrame"].saveResult("<?php echo $sStatus ?>"); } //]]> </script> </head> <body> </body> </html>
下面的一个是用表单序列化来处理post数据
html
//js
function formReady() { //get your reference to the form var oForm = document.forms[0]; var oHiddenForm = oIFrame.document.forms[0]; //iterate over each element in the form for (var i=0 ; i < oForm.elements.length; i++) { //get reference to the field var oField = oForm.elements[i]; //different behavior based on the type of field switch (oField.type) { //buttons - we don't care case "button": case "submit": case "reset": break; //checkboxes/radio buttons - only return the value if the controlis checked. case "radio": case "checkbox": if (!oField.checked) { break; } //text/hidden/password all return the value case "text": case "hidden": case "password": createInputField(oHiddenForm, oField.name, oField.value); break; default: switch(oField.tagName.toLowerCase()) { case "select": createInputField(oHiddenForm, oField.name, oField.options[oField.selectedIndex].value);//创建一个新的input break; default: createInputField(oHiddenForm, oField.name, oField.value); } } } oHiddenForm.action = oForm.action; oHiddenForm.submit();//表单form的submit方法提交 };
//
function createInputField(oHiddenForm, sName, sValue) {
oHidden = oIFrame.document.createElement("input");
oHidden.type = "hidden";
oHidden.name = sName;
oHidden.value = sValue;
oHiddenForm.appendChild(oHidden);
}
//创建一个隐藏的ifram
var oIFrame = null;
function createIFrame() {
var oIFrameElement = document.createElement("iframe");
oIFrameElement.style.display = "none";
oIFrameElement.name = "hiddenFrame";
oIFrameElement.id = "hiddenFrame";
document.body.appendChild(oIFrameElement);
oIFrame = frames["hiddenFrame"];
}
//
调用开始
function checkIFrame() {
if (!oIFrame) {
createIFrame();
}
//takes a cycle for some browers to recognize the new element
setTimeout(function () {
oIFrame.location = "ProxyForm.php";
}, 10);
}
//html
<form method="post" action="SaveCustomer.php" onsubmit="checkIFrame(); return false">
<p>Enter customer information to be saved:</p>
<p>Customer Name: <input type="text" name="txtName" value="" /><br />
Address: <input type="text" name="txtAddress" value="" /><br />
City: <input type="text" name="txtCity" value="" /><br />
State: <input type="text" name="txtState" value="" /><br />
Zip Code: <input type="text" name="txtZipCode" value="" /><br />
Phone: <input type="text" name="txtPhone" value="" /><br />
E-mail: <input type="text" name="txtEmail" value="" /></p>
<p><input type="submit" value="Save Customer Info" /></p>
</form>
<div id="divStatus"></div>
ProxyForm.php
<script type="text/javascript">//<![CDATA[ window.onload = function () { parent.formReady(); } //]]> </script> </head> <body> <form method="post" action="#"> </form> </body>
然后就是ajax登场了