1. ajax_func.js的代碼如下 :
//定義XMLHttpRequest實例
var?http_request?=?false;
//定義可復用的http請求發送函數,初始化、指定處理函數、發送請求的函數

function?send_request(method,?url,?content,?responseType,?callback)?
{
????http_request?=?false;
????//開始初始化XMLHttpRequest對象

????if(window.XMLHttpRequest)?
{
????????//Mozilla瀏覽器
????????http_request?=?new?XMLHttpRequest();

????????if(http_request.overrideMimeType)?
{
????????????//設置MIME類別
????????????http_request.overrideMimeType("text/xml");
????????}

????}?else?if(window.ActiveXObject)?
{
????????//IE瀏覽器

????????try?
{
????????????http_request?=?new?ActiveXObject("Msxml2.XMLHTTP");
????????}

????????catch?(e)?
{

????????????try?
{
????????????????http_request?=?new?ActiveXObject("Microsoft.XMLHTTP");
????????????}

????????????catch?(e)
{}
????????}
????}


????if(!http_request)?
{
????????//異常,創建對象實例失敗
????????window.alert("不能創建XMLHttpRequest對象實例.");
????????return?false;
????}


????if(responseType.toLowerCase()?==?"text"?||?responseType.toLowerCase()?==?"xml")?
{
????????http_request.onreadystatechange?=?callback;

????}??else?
{
????????window.alert("響應類別參數錯誤.");
????????return?false;
????}

????//確定發送請求的方式和URL以及是否一步執行下段代碼

????if(method.toLowerCase()?==?"get")?
{
????????http_request.open(method,?url,?true);

????}?else?if(method.toLowerCase()?==?"post")?
{
????????http_request.open(method,?url,?true);
????????http_request.setRequestHeader("Content-Type",?"application/x-www-form-urlencoded");

????}?else?
{
????????window.alert("http請求類別參數錯誤.");
????????return?false;
????}

????http_request.send(content);
}2. 回調函數舉例
1)處理返回文本格式信息的函數舉例(調用send_request方法時responseType為text)

function?processTextResponse()?
{

????if(http_request.readyState?==?4)?
{

????????if(http_request.status?==?200)?
{
????????????//信息已經成功返回,開始處理信息
????????????alert("Text文檔相應.");

????????}?else?
{
????????????alert("您所請求的頁面有異常.");
????????}
????}
}2)處理返回格式信息的函數舉例(調用send_request方法時responseType為xml)
function?processXMLResponse()?...{

????if(http_request.readyState?==?4)?...{

????????if(http_request.status?==?200)?...{
????????????//信息已經成功返回,開始處理信息
????????????alert("XML響應.");

????????}?else?...{
????????????alert("您所請求的頁面有異常.");
????????}
????}
}
posted on 2007-02-11 23:26
阿蜜果 閱讀(2266)
評論(8) 編輯 收藏 所屬分類:
Ajax