ajax发送多个请求

本文介绍如何在Internet Explorer浏览器中处理Ajax请求的限制,通过使用自定义的AsyncRequest方法来实现页面上的缓存加载,并展示了如何组织多个Ajax请求以避免代码混乱。

大家知道IE只能一次发送一个Ajax请求,你是否尝试过在一个页面上用Ajax请求多次,虽然可以实现我们发现代码很乱

我们来实现一个在页面呈现缓存的例子吧!
//获取Dom
function $(id) { return document.getElementById(id); }

思路:我们把要加载的缓存放在一个集合中,再迭代集合实现所有的获取缓存请求
var cache={page:"Index",id:"Courses",element:$("Courses")};
//page为加载的缓存页面 id缓存ID,element显示缓存的Dom对象

顺便插一句:这个例子用Jquery实现的了吗?可以尝试一下,呵呵,这几天好像跟Jquery有仇一样

上面定义了缓存对象,下面的代码就创建一个请求Ajax的方法,我们称之为: AsyncRequest
var xmlHttp = null;
function $AsyncRequest(request, callback) {
    this.method = request.method!=null&&request.method.toLowerCase()=="post"?"POST":"GET";
    this.url = request.url;
    this.params = request.params;
    this.dataType =request.dataType!=null&&request.dataType.toLowerCase() == "xml" ? "xml" : "text";
    this.async = request.async instanceof Boolean ? request.async : true;
    if (callback != null) {
        this.success = callback.success;
        this.error = callback.error;
        if (callback.start != null) callback.start();
    }
    if (xmlHttp == null) {
        if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
        else if(window.ActiveXObject)xmlHttp=new ActiveXObject("MSXML2.XMLHTTP")||new ActiveXObject("MICROSOFT.XMLHTTP");
        else{return false;}
    }

    var current = this;
   xmlHttp.open(this.method, this.url, this.async);
   xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                if (current.success != null)
                    current.success(current.dataType == "xml" ? xmlHttp.responseXml : xmlHttp.responseText);
            }
            else {
                if (current.error != null)
                    current.error(xmlHttp.responseText);
            }
        }
    }
    if (this.method== "POST")
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.send(this.params);
}

调用AsyncRequest方法实例:

  $AsyncRequest({ url:"http://127.0.0.1",method:"GET",async:true,dataType:"text" },

 { start: function () {//开始请求执行 },
   error:function(){//请求错误时执行},
   success: function (x) {//成功获取结果为x}
 });
//简单的就可以像下面这样调用
  $AsyncRequest({ url: "/default.htm"}, {
            success: function (x) {alert(x);}
        });

好了,下面我们来请求获取缓存内容并显示出来了!新建一个方法叫loadCache()
function loadCache(cache,callback) {
    this.requestUrl = "/handler/cacheASHtml.ashx?cache.page=" + cache.page +
        "&cache.guid=" + cache.id + (cache.params != null ? "&" + cache.params : "")+"&"+Math.random();
        var nodeName=cache.element.nodeName;
        if (nodeName != null && (nodeName == "DIV" || nodeName == "SPAN")) {
            var element = cache.element;
        } else { alert('不支持的元素(div,span)' + nodeName); return false; }
        $AsyncRequest({ url: this.requestUrl }, { start: function () { element.innerHTML = "加载中!"; },
            success: function (x) {element.innerHTML = x;if (callback != undefined) callback(); }
        });
}

我们加载显示一个缓存就可以这样调用
loadCache({ page: "Index", id: "NearIPrice", element: $("IPrice"));

我们发现请求一个请求并不难,但是要请求多个时候就遇到问题了..

先将要请求的缓存放到一个集合中:
Code_Closed_Image_121059" onclick="this.style.display='none'; document.getElementById('Code_Closed_Text_121059').style.display='none'; document.getElementById('Code_Open_Image_121059').style.display='inline'; document.getElementById('Code_Open_Text_121059').style.display='inline';" height="16" src="http://www.jzxue.com/System/uploads/allimg/091103/2122260.gif" width="11" align="top" alt="" />Code_Open_Image_121059" style="DISPLAY: none" onclick="this.style.display='none'; document.getElementById('Code_Open_Text_121059').style.display='none'; getElementById('Code_Closed_Image_121059').style.display='inline'; getElementById('Code_Closed_Text_121059').style.display='inline';" height="16" src="http://www.jzxue.com/System/uploads/allimg/091103/2122261.gif" width="11" align="top" alt="" />Code_Closed_Text_121059">CodeCode_Open_Text_121059" style="DISPLAY: none">
            window.caches = [{ page: _p, id: "VipSchoolArchive", element: $("VipArchives") },
                { page: _a, id: "DefaultPageVipArchivesRightPart", element: $("VipArchiveAd") },
                { page: _a, id: "DefaultPageVipArchivesBottomPart", element: $("VipArchiveAdBottom")}];

我们现在就要请求这所有的虎头缓存了!吃饭了直接上代码...呵呵

            window.caches = [{ page: _p, id: "VipSchoolArchive", element: $("VipArchives") },
                { page: _a, id: "DefaultPageVipArchivesRightPart", element: $("VipArchiveAd") },
                { page: _a, id: "DefaultPageVipArchivesBottomPart", element: $("VipArchiveAdBottom")}];

            loadCacheCollection(window.caches);

function loadCacheCollection(cacheArray) {
    cacheArray.reverse();
    var s = setInterval(function () {
        for (var i in cacheArray) {
            loadCache(cacheArray[i],
            function () {
                cacheArray.pop(cacheArray[i]);
                if (cacheArray.length == 0) clearInterval(s);
            });
        }
    }, 10);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值