1. 程式人生 > >Ajax 重構的步驟

Ajax 重構的步驟

log prototype scrip == *** pen gpo 回調函數 date

Ajax重構大致可以分為以下3三個步驟。

一 創建一個單獨的JS文件,名稱為AjaxRequest.js,並且在該文件中編寫重構Ajax 所需的代碼
具體代碼如下:
var net = new Object(); // 定義一個全局的變量
// 編寫構造函數
net.AjaxRequest = function(url,onload,onerror,method,params)
{
this.req = null;
this.onload = onload;
this.onerror=(onerror)?onerror:this.defaultError;
this.loadDate(url,method,params);
}
// 編寫用於初始化XMLHttpRequest 對象並指定處理函數,最後發送HTTP 請求的方法
net.AjaxRequest.prototype.loadDate = function(url,method,params)
{
if(!method) // 設置默認的請求方式為GET
{
method =“GET”;
}
if(window.XMLHttpRequest)
{ // 非IE 瀏覽器
this.req = newXMLHttpRequest(); // 創建XMLHttpRequest 對象
}
elseif(window.ActiveXObject)
{ // IE 瀏覽器
try
{
this.req= new ActiveXObject(“Microsoft.XMLHTTP”); // 創建XMLHttpRequest 對象
}
catch(e)
{
try
{
this.req = new ActiveXObject(“Msxml2.XMLHTTP”); // 創建XMLHttpRequest 對象
}
catch(e)
{
}
}
}
if(this.req)
{
try
{
varloader = this;
this.req.onreadystatechange= function()
{
net.AjaxRequest.onReadyState.call(loader);
}
this.req.open(method,url,true); // 建立對服務器的調用
if(method==“POST”)
{ // 如果提交方式為POST
this.req.setRequestHeader(“Content-Type”,“application /x-www-form-urlencoded”); // 設置請求的內容類型
this.req.setRequestHeader(“x-requested-with”,“ajax”); // 設置請求的發出者
}
this.req.send(params); // 發送請求
}
catch(err)
{
this.onerror.call(this); // 調用錯誤處理函數
}
}
}

// 重構回調函數
net.AjaxRequest.onReadyState = function()
{
var req =this.req;
var ready =req.readyState; // 獲取請求狀態
if(ready == 4)
{ // 請求完成
if(req.status== 200)
{ // 請求成功
this.onload.call(this);
}
else
{
this.onerror.call(this); // 調用錯誤處理函數
}
}
}
// 重構默認的錯誤處理函數
net.AjaxRequest.prototype.defaultError = function()
{
alert(“ 錯誤數據\ n \ n 回調狀態:”+ this.req.readyState +“\ n 狀態:”+ this.req.status);
}
二 在需要應用Ajax 的頁面中應用以下的語句包括步驟一中創建的JS 文件
<script language =“javascript”src =“AjaxRequest.js”> </script>

三 在應用Ajax 的頁面中編寫錯誤處理的方法,實例化Ajax 對象的方法和回調函數
具體代碼如下:
<script language =“javascript”>
/ ****************** 錯誤處理的方法************************************** /
function onerror()
{
alert(“ 您的操作有誤!”);
}
/ ****************** 實例化Ajax 對象的方法*********************** ****** /
function getInfo()
{
var loader = newnet.AjaxRequest(“getInfo.jsp?nocache =”+ new Date().getTime(),deal_getInfo,onerror,“GET”);
}
/ ************************ 回調函數*********************** *************** /
function deal_getInfo()
{
document.getElementById(“showInfo”).innerHTML= this.req.responseText;
}
</ script>

Ajax 重構的步驟