欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AJAXRequest v0.2

程序员文章站 2022-07-02 16:46:13
更新: 1)更改构造函数,使带参数,简化使用的步骤 类名:ajaxrequest 创建方法: var ajaxobj=new ajaxrequest(m...
更新:

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: vipxjw@163.com
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);
    }
}