用于顺序ajax请求的jQuery插件

时间:2013-08-26 22:59:54

标签: javascript ajax jquery jquery-plugins

我找不到jQuery的插件相当于这段代码:

function get() {
    var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5'],
        requests = [];
    for(i = 0; i < list.length; i++) {
        requests.push($.ajaxQueue({
            type: "POST",
            url: "/echo/html/",
            data: {html: list[i]},
            success: function(data) {
                $("div").append("Call " + data + "<br>");
            }
        }));
    }
    return requests;
}

$(document).on("click", "button", function(){
    $.when.apply(null, get()).then(function(){
        $.each(arguments, function(key, val){
            $("div").append(
              "Status: " + val[2].status + ", " +
              "responseText: " + val[2].responseText + "<br>"
            );
        });
    });
});

jsfiddle.net - 所有方法

jsfiddle.net - 逐个方法

这段代码在做什么:

  1. 允许将ajax请求配置为所有人的模板。
  2. 允许在每个ajax请求后执行成功函数。
  3. 允许在所有请求完成后执行函数,并提供对jqXHR对象数组的访问。
  4. 我如何看待这个插件:

    $.ajaxMulti({
        type: "POST",
        url: arrayOfUrls,
        data: {name: ""}
        // other ajax options
    })
    .oneDone(function(data){
    // manipulate with data (sequence observed)
    })
    .allDone(function(objects){
    // execute when all requests done
    });
    

    有用的链接:

1 个答案:

答案 0 :(得分:0)

这个怎么样:

example

HTML

<button id="btn">Send</button>

用法

$(document).ready(function(){
    //dummy data
    var requests = {
        types: [
            'POST',
            'PUT'
        ],
        urls: [
            '/url1',
            '/url2'
        ],
        data: [{
            name: 'name1'
        },{
            name: 'name2'
        }]
    };

    var ajaxian = new Ajaxian(requests, [
        function(){console.log('success')}, 
        function(){console.log('success2')}
    ]);

    $(ajaxian).bind('allrequestcomplete', function(){
        console.log('request sequence finished');
    });

    $(ajaxian).bind('requesterror', function(){
        console.log('request sequence failed');
    });

    $('#btn').bind('click', function(){
        ajaxian.startRequests();
    });
});

才算是Ajax

//Depricated method for jQuery 1.8 used, success -> done, error -> fail
function Ajaxian(requests, successHandlers){
    var self             = this;
    var me               = $(this);
    var _currentIndex    = 0;
    var _requests        = null;
    var _successHandlers = null;

    var construct = function(requests, successHandlers){
        _requests = requests;
        _successHandlers = successHandlers;
        requestHandler();
    }

    var getCurrentIndex = function(){
        //return _currentIndex++ too slow?
        var oldIndex = _currentIndex;
        _currentIndex++;
        return oldIndex;
    }

    var requestHandler = function(){
        console.log('event listener binded');
        console.log(me);

        me.bind('requestcomplete', function(data){
            //console.log(me);
            //console.log('event triggered');
            var index = getCurrentIndex();
            //console.log('step 0');
            if(_successHandlers[index - 1]){
                console.log(data);
                _successHandlers[index - 1](data);
            }           
            console.log('step 1');
            if(!_requests.urls[index]){
                me.trigger('allrequestcomplete');
                return;
            }

            prepareAndSendRequest(index);
        });

        me.bind('requestfailed', function(data){
            me.trigger('requesterror', data);
        })
    }

    var prepareAndSendRequest = function(index){
        console.log('current index: ' + index);
        var type = _requests.types[index];// ? _requests.types[index] : _requests.types[0];
        var url  = _requests.urls[index];// ? _requests.urls[index] : '';
        var data = _requests.data[index];// ? _requests.data[index] : {};            
        //console.log(type);
        //console.log(url);
        //console.log(data);
        doRequest(type, url, data);
    }

    var doRequest = function(type, url, data){        
        $.ajax({
            type: type,
            url: url,
            data: data            
        }).success(function(data){
            console.log(data);
            me.trigger('requestcomplete', data);
            //test
            //me.trigger('requestfailed', data);
        }).error(function(data){
            console.log(data);
            me.trigger('requestfailed');
            //test
            //me.trigger('requestcomplete', data);
        });
    }

    this.startRequests = function(){
        console.log('trigger');
        prepareAndSendRequest(getCurrentIndex());
    }

    construct(requests, successHandlers);
}