1

我正在使用使用 jquery 的延迟 Ajax。在按钮“TestAjax”的单击事件上,我将调用 2 个 WCF 服务。当他们完成加载时,我将执行一些逻辑。我的代码如下

this.TestAjax = function () {
        debugger;
        var flattened1;
        var flattened2;




        function callFirstService() {

            ViewModel.loadFirstService(1));

       }

        function callSecondService() {

            ViewModel.loadSecondService(2);
       }

        // Multiple Ajax Requests 
       $.when(callFirstService(), callSecondService()).done(function () {

           console.log("now we are will start logic);

           // logic here                



        });



};

在不同视图模型中调用服务的代码如下

  this.loadFirstService = function (id) {



        var input =
            {
                Id: id

            };


        $.ajax({
            url: "../RestService/someService",
            type: "PUT",
            contentType: 'application/json',
            processData: false,
            data: JSON.stringify(input),
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                alert(errorThrown);
            },

            success: function(allData) {
                var test = $.map(allData, function(item) {

                    return new Data1(item);
                });

                self.List1(test);




            }
        });

 };



 this.loadSecondService = function (id) {



        var input =
            {
                Id: id

            };


        $.ajax({
            url: "../RestService/someService",
            type: "PUT",
            contentType: 'application/json',
            processData: false,
            data: JSON.stringify(input),
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                alert(errorThrown);
            },

            success: function(allData) {
                var test = $.map(allData, function(item) {

                    return new Data2(item);
                });

                self.List2(test);




            }
        });

};

问题是它进入 $.when 并打印 console.log("now we are will start logic); 然后调用服务。我如何先调用服务,然后在成功命中服务时执行一些逻辑?

让我知道它是否不够清楚。

4

1 回答 1

1

您需要您的方法来返回延迟对象。

this.loadSecondService = function (id) {
    var input = {
        Id: id
    };
    return $.ajax({
        ...
    });

接下来,您需要处理接收数据的逻辑.done()

$.when(callFirstService(), callSecondService()).done(function (firstService,secondService) {
    console.log("Both services are done");
})
于 2013-03-19T18:07:02.640 回答