Ajax通信技术
Ajax通信技术:1.隐藏帧技术 2.XMLHttpRequest 3.基于图像的Ajax 4.动态脚本载入
一:隐藏帧(hidden frame)技术
1.技术说明:
将帧的宽度或高度设置为0像素来隐藏一个帧,使其不显示出来.然后从一个与用户交互的Web页面中的可见帧开始.
第一步:可见帧产生一个对隐藏帧的Javascript调用,这个调用可以简单地将隐藏帧重定向到另一个页面,也可以复杂传送表单数据.
第二步:向服务器发送一个请求.
第三步:从服务器上接收一个响应.由于处理的是帧,因此该响应必然是一个网页.
第四步:该网页必须包含服务器所请求的数据和一些Javascript,来把这些数据传给可见的帧.通常是通过返回网页中的onload事件来实现的,该网页在其全部载入之后调用可见帧中的函数.
2.隐藏帧的GET请求
HiddenFrameGetExample.aspx
<html>
<head>
<title>Hidden Frame GET Example</title>
</head>
<frameset rows="100%,0" style="border: 0px">
<frame name="displayFrame" src="DataDisplay.aspx" noresize="noresize" />
<frame name="hiddenFrame" src="about:blank" noresize="noresize" />
</frameset>
</html>
<html>
<head>
<title>Hidden Frame GET Example</title>
</head>
<frameset rows="100%,0" style="border: 0px">
<frame name="displayFrame" src="DataDisplay.aspx" noresize="noresize" />
<frame name="hiddenFrame" src="about:blank" noresize="noresize" />
</frameset>
</html>
DataDisplay.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Customer Account Information</title>
<script type="text/javascript">//<![CDATA[
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
top.frames["hiddenFrame"].location = "GetCustomerData.aspx?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>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Customer Account Information</title>
<script type="text/javascript">//<![CDATA[
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
top.frames["hiddenFrame"].location = "GetCustomerData.aspx?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>
GetCustomerData.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!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 runat="server">
<title>Get Customer Data</title>
<script runat="server">
protected string GetCustomerData()
{
//get the ID to retrieve
string id = Page.Request.QueryString["id"];
int intId = -1;
//make sure it's an integer
if (Int32.TryParse(id, out intId))
{
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("Select * from Customers where CustomerId={0}", id);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
}
catch (Exception ex)
{
return "Error occurred while trying to connect to database: " + ex.Message;
}
try
{
//run the query
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
string info = String.Format("{0}<br />{1}<br />{2}<br />{3}<br />{4}<br /><br />Phone: {5}<br /><a href=\"mailto:{6}\">{6}</a>",
reader.GetString(reader.GetOrdinal("Name")),
reader.GetString(reader.GetOrdinal("Address")),
reader.GetString(reader.GetOrdinal("City")),
reader.GetString(reader.GetOrdinal("State")),
reader.GetString(reader.GetOrdinal("Zip")),
reader.GetString(reader.GetOrdinal("Phone")),
reader.GetString(reader.GetOrdinal("Email"))
);
conn.Close();
return info;
}
else
{
conn.Close();
return String.Format("Customer with ID {0} doesn't exist.", id);
}
}
catch (Exception ex)
{
conn.Close();
return "Error occurred reading from DB: " + ex.Message;
}
}
else
{
return "Invalid customer ID.";
}
}
</script>
<script type="text/javascript">//<![CDATA[
window.onload = function () {
var divInfoToReturn = document.getElementById("divInfoToReturn");
top.frames["displayFrame"].displayCustomerInfo(divInfoToReturn.innerHTML);
};
//]]>
</script>
</head>
<body>
<div id="divInfoToReturn"><%= GetCustomerData() %></div>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!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 runat="server">
<title>Get Customer Data</title>
<script runat="server">
protected string GetCustomerData()
{
//get the ID to retrieve
string id = Page.Request.QueryString["id"];
int intId = -1;
//make sure it's an integer
if (Int32.TryParse(id, out intId))
{
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("Select * from Customers where CustomerId={0}", id);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
}
catch (Exception ex)
{
return "Error occurred while trying to connect to database: " + ex.Message;
}
try
{
//run the query
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
string info = String.Format("{0}<br />{1}<br />{2}<br />{3}<br />{4}<br /><br />Phone: {5}<br /><a href=\"mailto:{6}\">{6}</a>",
reader.GetString(reader.GetOrdinal("Name")),
reader.GetString(reader.GetOrdinal("Address")),
reader.GetString(reader.GetOrdinal("City")),
reader.GetString(reader.GetOrdinal("State")),
reader.GetString(reader.GetOrdinal("Zip")),
reader.GetString(reader.GetOrdinal("Phone")),
reader.GetString(reader.GetOrdinal("Email"))
);
conn.Close();
return info;
}
else
{
conn.Close();
return String.Format("Customer with ID {0} doesn't exist.", id);
}
}
catch (Exception ex)
{
conn.Close();
return "Error occurred reading from DB: " + ex.Message;
}
}
else
{
return "Invalid customer ID.";
}
}
</script>
<script type="text/javascript">//<![CDATA[
window.onload = function () {
var divInfoToReturn = document.getElementById("divInfoToReturn");
top.frames["displayFrame"].displayCustomerInfo(divInfoToReturn.innerHTML);
};
//]]>
</script>
</head>
<body>
<div id="divInfoToReturn"><%= GetCustomerData() %></div>
</body>
</html>
3.隐藏帧POST请求
HiddenFramePostExample.aspx
<html>
<head>
<title>Hidden Frame POST Example</title>
</head>
<frameset rows="100%,0" style="border: 0px">
<frame name="displayFrame" src="DataEntry.aspx" noresize="noresize" style="border: 0px" />
<frame name="hiddenFrame" src="about:blank" noresize="noresize" style="border: 0px" />
</frameset>
</html>
<html>
<head>
<title>Hidden Frame POST Example</title>
</head>
<frameset rows="100%,0" style="border: 0px">
<frame name="displayFrame" src="DataEntry.aspx" noresize="noresize" style="border: 0px" />
<frame name="hiddenFrame" src="about:blank" noresize="noresize" style="border: 0px" />
</frameset>
</html>
DataEntry.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<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.aspx" target="hiddenFrame">
<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>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<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.aspx" target="hiddenFrame">
<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>
</body>
</html>
SaveCustomer.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!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 runat="server">
<title>Create New Customer</title>
<script runat="server">
/// <summary>
/// Saves the customer data submitted to the form.
/// </summary>
/// <returns>A status message indicating if the data was saved.</returns>
protected string SaveCustomer()
{
//get information (replace apostrophes with double apostrophes to prevent SQL injection attacks)
string name = Page.Request.Form["txtName"].Replace("'", "''");
string address = Page.Request.Form["txtAddress"].Replace("'", "''");
string city = Page.Request.Form["txtCity"].Replace("'", "''");
string state = Page.Request.Form["txtState"].Replace("'", "''");
string zipCode = Page.Request.Form["txtZipCode"].Replace("'", "''");
string phone = Page.Request.Form["txtPhone"].Replace("'", "''");
string email = Page.Request.Form["txtEmail"].Replace("'", "''");
//status message
string status = "";
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("insert into Customers([Name], [Address], [City], [State], [Zip], [Phone], [Email]) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", name, address, city, state, zipCode, phone, email);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
}
catch (Exception ex)
{
return "Error occurred while trying to connect to database: " + ex.Message;
}
//do the insert
try {
con.Open();
int id = command.ExecuteNonQuery();
con.Close();
return String.Format("Added customer; customer ID is {0}", id);
} catch (Exception ex) {
return "An error occurred while inserting; customer not saved. " + ex.Message;
}
}
</script>
<script type="text/javascript">//<![CDATA[
window.onload = function () {
top.frames["displayFrame"].saveResult("<%= SaveCustomer() %>");
}
//]]>
</script>
</head>
<body>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!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 runat="server">
<title>Create New Customer</title>
<script runat="server">
/// <summary>
/// Saves the customer data submitted to the form.
/// </summary>
/// <returns>A status message indicating if the data was saved.</returns>
protected string SaveCustomer()
{
//get information (replace apostrophes with double apostrophes to prevent SQL injection attacks)
string name = Page.Request.Form["txtName"].Replace("'", "''");
string address = Page.Request.Form["txtAddress"].Replace("'", "''");
string city = Page.Request.Form["txtCity"].Replace("'", "''");
string state = Page.Request.Form["txtState"].Replace("'", "''");
string zipCode = Page.Request.Form["txtZipCode"].Replace("'", "''");
string phone = Page.Request.Form["txtPhone"].Replace("'", "''");
string email = Page.Request.Form["txtEmail"].Replace("'", "''");
//status message
string status = "";
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("insert into Customers([Name], [Address], [City], [State], [Zip], [Phone], [Email]) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", name, address, city, state, zipCode, phone, email);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
}
catch (Exception ex)
{
return "Error occurred while trying to connect to database: " + ex.Message;
}
//do the insert
try {
con.Open();
int id = command.ExecuteNonQuery();
con.Close();
return String.Format("Added customer; customer ID is {0}", id);
} catch (Exception ex) {
return "An error occurred while inserting; customer not saved. " + ex.Message;
}
}
</script>
<script type="text/javascript">//<![CDATA[
window.onload = function () {
top.frames["displayFrame"].saveResult("<%= SaveCustomer() %>");
}
//]]>
</script>
</head>
<body>
</body>
</html>
二:XMLHttpRequest
1.XMLHttp的GET请求
XHRGetExample.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHR GET Example</title>
<script type="text/javascript"src="zxml.js"></script>
<script type="text/javascript">
//<![CDATA[
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
var oXHR = zXmlHttp.createRequest();
oXHR.open("get", "GetCustomerData.aspx?id=" + sId, true);
oXHR.onreadystatechange = function () {
if (oXHR.readyState == 4) {
if (oXHR.status == 200 || oXHR.status == 304) {
displayCustomerInfo(oXHR.responseText);
} else {
displayCustomerInfo("An error occurred: " + oXHR.statusText); //statusText is not always accurate
}
}
};
oXHR.send(null);
}
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>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHR GET Example</title>
<script type="text/javascript"src="zxml.js"></script>
<script type="text/javascript">
//<![CDATA[
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
var oXHR = zXmlHttp.createRequest();
oXHR.open("get", "GetCustomerData.aspx?id=" + sId, true);
oXHR.onreadystatechange = function () {
if (oXHR.readyState == 4) {
if (oXHR.status == 200 || oXHR.status == 304) {
displayCustomerInfo(oXHR.responseText);
} else {
displayCustomerInfo("An error occurred: " + oXHR.statusText); //statusText is not always accurate
}
}
};
oXHR.send(null);
}
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>
GetCustomerData.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
// Set the content-type
Response.ContentType = "text/plain";
Response.ContentEncoding = Encoding.UTF8;
//get the ID to retrieve
string id = "";
if (Page.Request.QueryString["id"] != null)
{
id = Page.Request.QueryString["id"].Replace("'", "''");
}
//the message to return
string message = "";
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("Select * from Customers where CustomerId={0}", id);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
}
catch (Exception ex)
{
message = "Error occurred while trying to connect to database: " + ex.Message;
}
try
{
//run the query
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = String.Format("{0}<br />{1}<br />{2}<br />{3}<br />{4}<br /><br />Phone: {5}<br /><a href=\"mailto:{6}\">{6}</a>",
reader.GetString(reader.GetOrdinal("Name")),
reader.GetString(reader.GetOrdinal("Address")),
reader.GetString(reader.GetOrdinal("City")),
reader.GetString(reader.GetOrdinal("State")),
reader.GetString(reader.GetOrdinal("Zip")),
reader.GetString(reader.GetOrdinal("Phone")),
reader.GetString(reader.GetOrdinal("Email"))
);
conn.Close();
}
else
{
conn.Close();
message = String.Format("Customer with ID {0} doesn't exist.", id);
}
}
catch (Exception ex)
{
conn.Close();
message = "Error occurred reading from DB: " + ex.Message;
}
Response.Write(message);
}
</script>
2.XMLHttp的POST请求<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
// Set the content-type
Response.ContentType = "text/plain";
Response.ContentEncoding = Encoding.UTF8;
//get the ID to retrieve
string id = "";
if (Page.Request.QueryString["id"] != null)
{
id = Page.Request.QueryString["id"].Replace("'", "''");
}
//the message to return
string message = "";
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("Select * from Customers where CustomerId={0}", id);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
}
catch (Exception ex)
{
message = "Error occurred while trying to connect to database: " + ex.Message;
}
try
{
//run the query
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = String.Format("{0}<br />{1}<br />{2}<br />{3}<br />{4}<br /><br />Phone: {5}<br /><a href=\"mailto:{6}\">{6}</a>",
reader.GetString(reader.GetOrdinal("Name")),
reader.GetString(reader.GetOrdinal("Address")),
reader.GetString(reader.GetOrdinal("City")),
reader.GetString(reader.GetOrdinal("State")),
reader.GetString(reader.GetOrdinal("Zip")),
reader.GetString(reader.GetOrdinal("Phone")),
reader.GetString(reader.GetOrdinal("Email"))
);
conn.Close();
}
else
{
conn.Close();
message = String.Format("Customer with ID {0} doesn't exist.", id);
}
}
catch (Exception ex)
{
conn.Close();
message = "Error occurred reading from DB: " + ex.Message;
}
Response.Write(message);
}
</script>
XHRPostExample.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHR POST Example</title>
<script type="text/javascript"src="zxml.js"></script>
<script type="text/javascript">
//<![CDATA[
function sendRequest() {
var oForm = document.forms[0];
var sBody = getRequestBody(oForm);
var oXHR = zXmlHttp.createRequest();
oXHR.open("post", oForm.action, true);
oXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXHR.onreadystatechange = function () {
if (oXHR.readyState == 4) {
if (oXHR.status == 200) {
saveResult(oXHR.responseText);
} else {
saveResult("An error occurred: " + oXHR.statusText);
}
}
};
oXHR.send(sBody);
}
function encodeNameAndValue(sName, sValue) {
var sParam = encodeURIComponent(sName);
sParam += "=";
sParam += encodeURIComponent(sValue);
return sParam;
}
function getRequestBody(oForm) {
//array to hold the params
var aParams = new Array();
//get your reference to the form
var oForm = 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 control is checked.
case "radio":
case "checkbox":
if (!oField.checked) {
break;
} //End: if
//text/hidden/password all return the value
case "text":
case "hidden":
case "password":
aParams.push(encodeNameAndValue(oField.name, oField.value));
break;
//everything else
default:
switch(oField.tagName.toLowerCase()) {
case "select":
aParams.push(encodeNameAndValue(oField.name, oField.options[oField.selectedIndex].value));
break;
default:
aParams.push(encodeNameAndValue(oField.name, oField.value));
}
}
}
return aParams.join("&");
}
function saveResult(sMessage) {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "Request completed: " + sMessage;
}
//]]>
</script>
</head>
<body>
<form method="post" action="SaveCustomer.aspx" onsubmit="sendRequest(); 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>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHR POST Example</title>
<script type="text/javascript"src="zxml.js"></script>
<script type="text/javascript">
//<![CDATA[
function sendRequest() {
var oForm = document.forms[0];
var sBody = getRequestBody(oForm);
var oXHR = zXmlHttp.createRequest();
oXHR.open("post", oForm.action, true);
oXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXHR.onreadystatechange = function () {
if (oXHR.readyState == 4) {
if (oXHR.status == 200) {
saveResult(oXHR.responseText);
} else {
saveResult("An error occurred: " + oXHR.statusText);
}
}
};
oXHR.send(sBody);
}
function encodeNameAndValue(sName, sValue) {
var sParam = encodeURIComponent(sName);
sParam += "=";
sParam += encodeURIComponent(sValue);
return sParam;
}
function getRequestBody(oForm) {
//array to hold the params
var aParams = new Array();
//get your reference to the form
var oForm = 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 control is checked.
case "radio":
case "checkbox":
if (!oField.checked) {
break;
} //End: if
//text/hidden/password all return the value
case "text":
case "hidden":
case "password":
aParams.push(encodeNameAndValue(oField.name, oField.value));
break;
//everything else
default:
switch(oField.tagName.toLowerCase()) {
case "select":
aParams.push(encodeNameAndValue(oField.name, oField.options[oField.selectedIndex].value));
break;
default:
aParams.push(encodeNameAndValue(oField.name, oField.value));
}
}
}
return aParams.join("&");
}
function saveResult(sMessage) {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "Request completed: " + sMessage;
}
//]]>
</script>
</head>
<body>
<form method="post" action="SaveCustomer.aspx" onsubmit="sendRequest(); 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>
</body>
</html>
SaveCustomer.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
// Set the content-type
Response.ContentType = "text/plain";
Response.ContentEncoding = Encoding.UTF8;
//get information (replace apostrophes with double apostrophes to prevent SQL injection attacks)
string name = Page.Request.Form["txtName"].Replace("'", "''");
string address = Page.Request.Form["txtAddress"].Replace("'", "''");
string city = Page.Request.Form["txtCity"].Replace("'", "''");
string state = Page.Request.Form["txtState"].Replace("'", "''");
string zipCode = Page.Request.Form["txtZipCode"].Replace("'", "''");
string phone = Page.Request.Form["txtPhone"].Replace("'", "''");
string email = Page.Request.Form["txtEmail"].Replace("'", "''");
//the message to send back
string message = "";
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("insert into Customers([Name], [Address], [City], [State], [Zip], [Phone], [Email]) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", name, address, city, state, zipCode, phone, email);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
//do the insert
try
{
conn.Open();
int id = command.ExecuteNonQuery();
conn.Close();
message = "Added customer.";
}
catch (Exception ex)
{
conn.Close();
message = "An error occurred while inserting; customer not saved. " + ex.Message;
}
}
catch (Exception ex)
{
message = "Error occurred while trying to connect to database: " + ex.Message;
return;
}
Response.Write(message);
}
</script>
注:zXml程序库可以从www.nczonline.net/downloads/下载(未完,待续)
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
// Set the content-type
Response.ContentType = "text/plain";
Response.ContentEncoding = Encoding.UTF8;
//get information (replace apostrophes with double apostrophes to prevent SQL injection attacks)
string name = Page.Request.Form["txtName"].Replace("'", "''");
string address = Page.Request.Form["txtAddress"].Replace("'", "''");
string city = Page.Request.Form["txtCity"].Replace("'", "''");
string state = Page.Request.Form["txtState"].Replace("'", "''");
string zipCode = Page.Request.Form["txtZipCode"].Replace("'", "''");
string phone = Page.Request.Form["txtPhone"].Replace("'", "''");
string email = Page.Request.Form["txtEmail"].Replace("'", "''");
//the message to send back
string message = "";
//database information
string dataSourceName = @"localhost\SQLEXPRESS";
string catalogName = "ProAjax";
string connectString = String.Format("server={0};database={1};uid=sa;pwd=123", dataSourceName, catalogName);
string query = String.Format("insert into Customers([Name], [Address], [City], [State], [Zip], [Phone], [Email]) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", name, address, city, state, zipCode, phone, email);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
//do the insert
try
{
conn.Open();
int id = command.ExecuteNonQuery();
conn.Close();
message = "Added customer.";
}
catch (Exception ex)
{
conn.Close();
message = "An error occurred while inserting; customer not saved. " + ex.Message;
}
}
catch (Exception ex)
{
message = "Error occurred while trying to connect to database: " + ex.Message;
return;
}
Response.Write(message);
}
</script>
posted on 2009-05-22 16:45 huanjian9999 阅读(403) 评论(0) 编辑 收藏 举报