当前位置: 移动技术网 > IT编程>脚本编程>Ajax > 一个简单的AJAX请求类

一个简单的AJAX请求类

2017年12月12日  | 移动技术网IT编程  | 我要评论
在给blog加上无刷新搜索和即时验证检测后,又看了下代码,感觉太过麻烦,就把xmlhttprequest请求封装到一个类里面,用起来方便多了,不用记那么多代码,什么创建xmlhttprequest对象什么的,这部分代码也是重用性比较高的~已经打包,在日志的末尾下载。

要看效果的话点开侧边栏里的日志搜索,里面有一个无刷新搜索,就是了,或者在阅读日志或留言簿里的注册码那里有即时检测,如果不输入验证码或者输错了验证码,输入框都会变红的^_^

类名:ajaxrequest

创建方法:var ajaxobj=new ajaxrequest;,如果创建失败则返回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">
var ajaxobj=new ajaxrequest;    // 创建ajax对象
ajaxobj.method="get";   // 设置请求方式为get
ajaxobj.url="default.asp"  // url为default.asp
// 设置回调函数,输出响应内容
ajaxobj.callback=function(xmlobj) {
     document.write(xmlobj.responsetext);
}
ajaxobj.send();    // 发送请求

复制代码 代码如下:

// ajax类
function ajaxrequest() {
    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="post";
    this.url;
    this.async=true;
    this.content="";
    this.callback=function(cbobj) {return;}
    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);
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网