DIV CSS 佈局教程網

AJAXRequest v0.2
編輯:AJAX基礎知識     
更新:

1)更改構造函數,使帶參數,簡化使用的步驟

類名:AJAXRequest

創建方法:

var ajaxobj=new AJAXRequest(method,url,async,content,callback);

如果創建失敗則返回false

屬性:method  -  請求方法,字符串,POST或者GET,默認為POST

   url         -  請求URL,字符串,默認為空

   async     -  是否異步,true為異步,false為同步,默認為true

   content -  請求的內容,如果請求方法為POST需要設定此屬性,默認為空

   callback  - 回調函數,即返回響應內容時調用的函數,默認為直接返回,回調函數有一個參數為XMLHttpRequest對象,即定義回調函數時要這樣:function mycallback(xmlobj)

方法:send()     -  發送請求,無參數

一個例子:

復制代碼 代碼如下:
<script type="text/javascript" src="ajaxrequest.js"></script>
<script type="text/javascript">
// 請求方式GET,URL為default.asp,異步
var ajaxobj=new AJAXRequest("GET","default.asp",true,null,MyCallback);    // 創建AJAX對象
ajaxobj.send();    // 發送請求
function MyCallback(xmlObj) {
     document.write(xmlobj.responseText);
}

ajaxrequest.js
復制代碼 代碼如下:
/*------------------------------------------
Author: xujiwei
Website: http://www.xujiwei.cn
E-mail: [email protected]
Copyright (c) 2006, All Rights Reserved
------------------------------------------*/
function AJAXRequest(pmethod,purl,pasync,pcontent,pcallback) {
    var xmlObj = false;
    var CBfunc,ObjSelf;
    ObjSelf=this;
    try { xmlObj=new XMLHttpRequest; }
    catch(e) {
        try { xmlObj=new ActiveXObject("MSXML2.XMLHTTP"); }
        catch(e2) {
            try { xmlObj=new ActiveXObject("Microsoft.XMLHTTP"); }
            catch(e3) { xmlObj=false; }
        }
    }
    if (!xmlObj) return false;
    this.method=pmethod;
    this.url=purl;
    this.async=pasync;
    this.content=pcontent;
    this.callback=pcallback;
    this.send=function() {
        if(!this.method||!this.url||!this.async) return false;
        xmlObj.open (this.method, this.url, this.async);
        if(this.method=="POST") xmlObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlObj.onreadystatechange=function() {
            if(xmlObj.readyState==4) {
                if(xmlObj.status==200) {
                    ObjSelf.callback(xmlObj);
                }
            }
        }
        if(this.method=="POST") xmlObj.send(this.content);
        else xmlObj.send(null);
    }
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved