Ajax通信技术2
Ajax通信技术:1.隐藏帧技术 2.XMLHttpRequest 3.基于图像的Ajax 4.动态脚本载入
三.基于图像的Ajax
1.GET请求
四.动态脚本载入
三.基于图像的Ajax
1.GET请求
ImageGetExample.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Example 1</title>
<script type="text/javascript">
//<![CDATA[
function getCookie(sName) {
var sRE = "(?:; )?" + encodeURIComponent(sName) + "=([^;]*);?";
var oRE = new RegExp(sRE);
if (oRE.test(document.cookie)) {
return decodeURIComponent(RegExp["$1"]);
} else {
return null;
}
}
function deleteCookie(sName) {
document.cookie = encodeURIComponent(sName) + "=0; expires=Thu, 1 Jan 1970 00:00:00 UTC; path=/";
}
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
var oImg = new Image();
oImg.onload = function () {
displayCustomerInfo(getCookie("info"));
deleteCookie("info");
};
oImg.onerror = function () {
displayCustomerInfo("An error occurred while processing the request.");
};
oImg.src = "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>
<title>Image Example 1</title>
<script type="text/javascript">
//<![CDATA[
function getCookie(sName) {
var sRE = "(?:; )?" + encodeURIComponent(sName) + "=([^;]*);?";
var oRE = new RegExp(sRE);
if (oRE.test(document.cookie)) {
return decodeURIComponent(RegExp["$1"]);
} else {
return null;
}
}
function deleteCookie(sName) {
document.cookie = encodeURIComponent(sName) + "=0; expires=Thu, 1 Jan 1970 00:00:00 UTC; path=/";
}
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
var oImg = new Image();
oImg.onload = function () {
displayCustomerInfo(getCookie("info"));
deleteCookie("info");
};
oImg.onerror = function () {
displayCustomerInfo("An error occurred while processing the request.");
};
oImg.src = "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" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
//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 [Name] 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 = reader.GetString(reader.GetOrdinal("Name"));
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.Cookies["info"].Value = message;
Response.Redirect("pixel.gif");
}
</script>
2.POST请求<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
//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 [Name] 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 = reader.GetString(reader.GetOrdinal("Name"));
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.Cookies["info"].Value = message;
Response.Redirect("pixel.gif");
}
</script>
ImagePostExample.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Example 2</title>
<script type="text/javascript">
//<![CDATA[
function sendRequest() {
var oForm = document.forms[0];
var sQueryString = "id=" + encodeURIComponent(oForm.txtID.value)
+ "&name=" + encodeURIComponent(oForm.txtName.value);
var oImg = new Image();
oImg.onload = function () {
var divStatus = document.getElementById("divStatus");
switch(this.width) {
case 1:
divStatus.innerHTML = "Customer name updated successfully.";
break;
case 2:
divStatus.innerHTML = "Invalid customer ID; name not updated.";
break;
default:
divStatus.innerHTML = "An error occurred while trying to process this request.";
}
};
oImg.onerror = function () {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "An error occurred while trying to process this request.";
};
oImg.src = "UpdateCustomerName.aspx?" + sQueryString;
}
//]]>
</script>
</head>
<body>
<form method="post" action="UpdateCustomerName.aspx" onsubmit="sendRequest(); return false">
<p>Enter the customer ID to update: <input type="text" name="txtID" value="" /></p>
<p>Enter the new customer name: <input type="text" name="txtName" value="" /></p>
<p><input type="submit" value="Update Customer Name" /></p>
</form>
<div id="divStatus"></div>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Example 2</title>
<script type="text/javascript">
//<![CDATA[
function sendRequest() {
var oForm = document.forms[0];
var sQueryString = "id=" + encodeURIComponent(oForm.txtID.value)
+ "&name=" + encodeURIComponent(oForm.txtName.value);
var oImg = new Image();
oImg.onload = function () {
var divStatus = document.getElementById("divStatus");
switch(this.width) {
case 1:
divStatus.innerHTML = "Customer name updated successfully.";
break;
case 2:
divStatus.innerHTML = "Invalid customer ID; name not updated.";
break;
default:
divStatus.innerHTML = "An error occurred while trying to process this request.";
}
};
oImg.onerror = function () {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "An error occurred while trying to process this request.";
};
oImg.src = "UpdateCustomerName.aspx?" + sQueryString;
}
//]]>
</script>
</head>
<body>
<form method="post" action="UpdateCustomerName.aspx" onsubmit="sendRequest(); return false">
<p>Enter the customer ID to update: <input type="text" name="txtID" value="" /></p>
<p>Enter the new customer name: <input type="text" name="txtName" value="" /></p>
<p><input type="submit" value="Update Customer Name" /></p>
</form>
<div id="divStatus"></div>
</body>
</html>
UpdateCustomerName.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ 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 = "image/jpeg";
//width of the image
int imageWidth = 1;
//get information (replace apostrophes with double apostrophes to prevent SQL injection attacks)
string name = Page.Request.QueryString["name"].Replace("'", "''");
string id = "";
if (Page.Request.QueryString["id"] != null)
{
id = Page.Request.QueryString["id"].Replace("'", "''");
}
else
{
imageWidth = 2;
}
//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("Update Customers set [Name] = '{0}' where CustomerId={1}", name, id);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
//do the update
try
{
conn.Open();
int rows = command.ExecuteNonQuery();
if (rows == 0) //if no rows were updated, then the customer ID is invalid
{
imageWidth = 2;
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
imageWidth = 3;
}
}
catch (Exception ex)
{
imageWidth = 3;
}
Bitmap image = new Bitmap(imageWidth, 1);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
image.Dispose();
}
</script>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ 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 = "image/jpeg";
//width of the image
int imageWidth = 1;
//get information (replace apostrophes with double apostrophes to prevent SQL injection attacks)
string name = Page.Request.QueryString["name"].Replace("'", "''");
string id = "";
if (Page.Request.QueryString["id"] != null)
{
id = Page.Request.QueryString["id"].Replace("'", "''");
}
else
{
imageWidth = 2;
}
//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("Update Customers set [Name] = '{0}' where CustomerId={1}", name, id);
//database objects
SqlConnection conn = null;
SqlCommand command = null;
try
{
//try to connect
conn = new SqlConnection(connectString);
command = new SqlCommand(query, conn);
//do the update
try
{
conn.Open();
int rows = command.ExecuteNonQuery();
if (rows == 0) //if no rows were updated, then the customer ID is invalid
{
imageWidth = 2;
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
imageWidth = 3;
}
}
catch (Exception ex)
{
imageWidth = 3;
}
Bitmap image = new Bitmap(imageWidth, 1);
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
image.Dispose();
}
</script>
四.动态脚本载入
DynamicScriptLoadingExample.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dynamic Script Loading Example 2</title>
<script type="text/javascript">
//<![CDATA[
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = "GetCustomerData.aspx?id=" + sId + "&callback=displayCustomerInfo";
document.body.appendChild(oScript);
}
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>Dynamic Script Loading Example 2</title>
<script type="text/javascript">
//<![CDATA[
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = "GetCustomerData.aspx?id=" + sId + "&callback=displayCustomerInfo";
document.body.appendChild(oScript);
}
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#" ContentType="text/javascript" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
//get the ID to retrieve
string id = "";
if (Page.Request.QueryString["id"] != null)
{
id = Page.Request.QueryString["id"].Replace("'", "''");
}
//the callback function to call
string callbackFunction = Page.Request.QueryString["callback"];
//the message to return
string info = "";
//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)
{
info = "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();
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();
}
else
{
conn.Close();
info = String.Format("Customer with ID {0} doesn't exist.", id);
}
}
catch (Exception ex)
{
conn.Close();
info = "Error occurred reading from DB: " + ex.Message;
}
Response.Write(String.Format("{0}(\"{1}\")", callbackFunction, info.Replace("\"", "\\\"").Replace("\n", "\\n")));
}
</script>
(未完,待续)
<%@ Page Language="C#" ContentType="text/javascript" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
//get the ID to retrieve
string id = "";
if (Page.Request.QueryString["id"] != null)
{
id = Page.Request.QueryString["id"].Replace("'", "''");
}
//the callback function to call
string callbackFunction = Page.Request.QueryString["callback"];
//the message to return
string info = "";
//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)
{
info = "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();
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();
}
else
{
conn.Close();
info = String.Format("Customer with ID {0} doesn't exist.", id);
}
}
catch (Exception ex)
{
conn.Close();
info = "Error occurred reading from DB: " + ex.Message;
}
Response.Write(String.Format("{0}(\"{1}\")", callbackFunction, info.Replace("\"", "\\\"").Replace("\n", "\\n")));
}
</script>
posted on 2009-05-22 17:15 huanjian9999 阅读(207) 评论(0) 编辑 收藏 举报