AJAX:”Asynchronous JavaScript and XML”
中文意思:異步JavaScript和XML。指一種創建
交互式網頁應用的網頁開發技術。AJAX並非縮寫詞,而是由Jesse James Gaiiett創造的名詞。
AJAX不是指一種單一的技術,而是有機地利用了一系列相關的技術:
1、web標准( Standards-Based Presentation )XHTML+CSS的表示;
2、使用 DOM( Document Object Model )進行動態顯示及交互;
3、使用 XML 和 XSLT 進行數據交換及相關操作,使用 XMLHttpRequest 進行異步數據查詢、檢索.
簡單理解為:JavaScript + XMLHttpRequest + CSS +服務器端 的集合.廢話少說,下面直接上代碼(這里我只寫以Post方式發送請求的代碼,關於JQuery中使用ajax跟以Get方式發送請求,我就不寫了),在下面的代碼中,我會從建立異步對象,到在WebForm頁面中使用異步對象來說說我的體會。
1、用js創建兼容瀏覽器的ajax異步對象
function createAjax() {
var ajaxObject = false;
try {
ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
ajaxObject = false;
}
}
if (!ajaxObject && typeof (XMLHttpRequest) != 'undefinded') {
ajaxObject = new XMLHttpRequest();
}
return ajaxObject;
}
2、頁面中ajax的使用
<script type="text/javascript">
var ajaxObject;
window.onload = function () {
ajaxObject = createAjax();
getControl("btnOK").onclick = submitData1;
}
function submitData1() {
var txtName = getControl("txtName").value;
//以Post方式請求發送請求
ajaxObject.open("POST", "ResponseEnd.aspx", true);
//以Post方式發送異步請求需要設置請求頭
ajaxObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxObject.onreadystatechange = function () {
if (ajaxObject.readyState == 4) {
//狀態200表示異步對象已經完全接收完服務器響應的數據
if (ajaxObject.status == 200) {
var res = ajaxObject.responseText;
alert(res);
}
}
}
//發送異步請求(Post方式發送請求在send里面書寫自己要發送給服務器的參數)
ajaxObject.send("flag=1&name=" + txtName);
}
</script>
3、后台頁面ResponseEnd.aspx.cs對數據的處理
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
namespace
Web
{
public
partial
class
ResponseEnd : System.Web.UI.Page
{
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(!
string
.IsNullOrEmpty(Request[
"flag"
]))
{
ShuChu();
}
}
private
void
ShuChu()
{
#region 方法一
//try
//{
// string name = Request["name"];
// Response.Write(name);
//}
//catch (Exception ex)
//{
// throw new Exception(ex.Message);
//}
//finally
//{
// Response.End();
//}
#endregion
#region 方法二
//try
//{
// string name = Request["name"];
// Response.Write(name);
// this.Page.Visible = false;
// Context.ApplicationInstance.CompleteRequest();
//}
//catch (Exception ex)
//{
// throw new Exception(ex.Message);
//}
#endregion
try
{
string
name = Request[
"name"
];
Response.Write(name);
Response.End();
}
catch
(System.Threading.ThreadAbortException ex)
{
}
catch
(Exception ex)
{
throw
new
Exception(ex.Message);
}
}
}
}
|