有没有一种方法,以确保后续调用执行之前的第一个AJAX调用完成? [英] Is there a way to ensure that the first AJAX call completes before the subsequent call executes?

查看:104
本文介绍了有没有一种方法,以确保后续调用执行之前的第一个AJAX调用完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以用户的时间表画成HTML表格通过jQuery使consecuitve异步Ajax调用。 每个响应返回一个包含两个表的JSON序列化数据集:计划活动之一,另一个包含用户信息。

我遇到的问题是,用户的信息似乎搞混了用户事件。即,有时用户onfo不 改变不同的反应如此安排的活动都与不正确的用户。如果我的AJAX异步属性设置为false,一切都很好。

整点是一个显示方案之一是将数据返回使页面冻结,直到所有的数据被返回,而不是。

有没有一种方法,以确保第一JAX调用完成后续调用执行之前?

(也许是我的异步设置为false理解是incorrrect。难道这不意味着所有的数据之前,code将继续执行收获?)

下面是我目前的做法:

  //当页面加载
    $(文件)。就绪(函数(){
        //获取日期范围
        调试器;
    // GetStartDate(),GetEndDate()填充日期范围
    // PopulateParams()会替其余参数
        $。当(GetStartDate(),GetEndDate())
        。然后(函数(){
            PopulateParams();
            GetUserSchedule();
        })
        .fail(函数(){
            failureAlertMsg();

        })
    });

    //返回计划为选定的开始和结束日期之间列出的每个人
    功能GetUserSchedule(){
         对于(VAR I = 0; I< arrRequests.length;我++){
            $。当(
            // Ajax调用Web方法,传递字符串
            $阿贾克斯({
                键入:POST,
                网址:网址/ Default.aspx的/ GetSchedules
                数据:arrRequests [I]中,//示例数据:{用户ID:6115,的startDate:\2011/7/1 \,结束日期:\2011年7月31日\ MoreVals:瓦尔斯}的contentType:应用/ JSON
                数据类型:JSON,
                成功:SuccessFunction,
                错误:函数(D){警报('失败'+ d.responseText +\ n请刷新页面重试或联系管理员'); }
            })
            )
            。然后(函数(){

            }
            );
        }
    }

    //在成功完成调用Web方法,涂料时间表成HTML表格对每个用户
    函数SuccessFunction(数据){
        如果(数据= NULL和放大器;!&安培; data.d = NULL和放大器;!&安培;!data.d.Temp = NULL){

        //调用一组函数作画进度到HTML表格
        //数据包含两个表:一个包含用户信息,另一个包含的行信息为每个事件为用户
        //有时,用户信息是不正确的用户或事件是不正确的用户
    }
 

解决方案

下面是我如何解决这个问题。希望这将帮助别人。可能有一些错别字......这仅仅是为了显示总体思路。我打电话给我的GetData方法递归:

  //当页面加载
    $(文件)。就绪(函数(){
        FunctionToBegin();
    });


    //填充含AJAX调用PARAMS和调用方法
    功能FunctionToBegin(){
        //填充任何需要的PARAMS这里,包括所需的第一AJAX调用的第一个参数

        //下面块使用jQuery.Deferred()的对象,在jQuery的1.5引入
        //见http://api.jquery.com/category/deferred-object/
        //对象允许我们连锁回调,**在指定的顺序**

        //获取日期范围
        $。当(GetStartDate(),GetEndDate())
            。然后(函数(){
      变量$ trCurrent = $('的DataRow:第一。');
                //传入第一用户ID
                的GetData($ trCurrent.find(TD:第一')文本()修剪());
            })
                .fail(函数(){
                    failureAlertMsg();
                }
           )
    }


    功能的GetData(用户ID){
        //获取用户ID
        用户ID =用户ID;
        //创建一个包含所需数据的JSON字符串来获取所需的数据
        jsonTextStringified = NULL;
        jsonTextStringified = JSON.stringify({用户ID:用户ID,的startDate:的startDate,结束日期:结束日期,AdditionalValues​​:AdditionalValues​​});
        // Ajax调用Web方法,传递字符串
        $阿贾克斯({
            键入:POST,
            网址:/URL/default.aspx/WebMethod
            数据:jsonTextStringified,
            的contentType:应用/ JSON
            数据类型:JSON,
            异步:真正的,
            成功:SuccessFunction,
            错误:函数(D){警报('失败'+ d.responseText +\ n请刷新页面重试或联系管理员'); }
        });
    }

    函数SuccessFunction(数据){
      如果(数据= NULL和放大器;!&安培; data.d = NULL和放大器;!&安培;!data.d.Temp = NULL){
    //做有用的东西


    //处理下一个用户ID
            nextUserID =的someMethod();
            如果(nextUserID!= 0){的GetData(nextUserID)}
        }
        其他 {
                 nextUserID =的someMethod();
                 如果(nextUserID!= 0){的GetData(nextUserID)}
            }
        }
    }
 

该大纲允许每个异步调用处理下一个电话之前完成。换句话说,该组的异步调用不执行一次全部,因此,不锤负责返回数据的Web方法。以我为例,我是返回一个包含两个表的数据集和返回的桌子是不一致准确的,除非我设置异步标志设置为false(不接受我的目的),或跟着oulined方法。

I am attempting to make consecuitve async ajax calls in order to paint user's schedules into a HTML table via jQuery. Each response returns a JSON serialized DataSet containing two tables: one of scheduled events and the other contains user info.

The problem I am having is that the user info seems to get mixed up with user events. That is, sometimes the user onfo doesn't change for different responses so the scheduled events are tied to an incorrect user. If I set the AJAX async property to false, all is well.

The whole point is to display the schedules one by one as the data is returned instead of making the page freeze until all data is returned.

Is there a way to ensure that the first JAX call completes before the subsequent call executes?

(Perhaps my understanding of setting async to false is incorrrect. Doesn't it mean that all data is harvested before code execution continues?)

Here is my current approach:

        //  When page loads
    $(document).ready(function () {
        // Get date range            
        debugger;
    //GetStartDate(), GetEndDate() populates date range
    //PopulateParams() does that for remaining parameters
        $.when(GetStartDate(), GetEndDate())
        .then(function () {
            PopulateParams();
            GetUserSchedule();
        })
        .fail(function () {
            failureAlertMsg();

        })
    });

    // Returns schedule for each person listed in between selected start and end dates
    function GetUserSchedule() {
         for (var i = 0; i < arrRequests.length; i++) {
            $.when(
            // Ajax call to web method, passing in string
            $.ajax({
                type: "POST",
                url: URL/default.aspx/GetSchedules",
                data: arrRequests[i],   // example data: {"UserId":"6115","startDate":"\"7/1/2011\"","endDate":"\"7/31/2011\MoreVals: Vals}                    contentType: "application/json",
                dataType: "json",
                success: SuccessFunction,
                error: function (d) { alert('Failed' + d.responseText + '\nPlease refresh page to try again or contact administrator'); }
            })
            )
            .then(function () {

            }
            );
        }
    }

    // On successful completion of call to web method, paint schedules into HTML table for each user
    function SuccessFunction(data) {            
        if (data != null && data.d != null && data.d.Temp != null) {

        // Calls a bunch of functions to paint schedule onto HTML table
        // Data contains two tables: one contains user info and the other contains rows of info for each event for user
        // at times, the user info is not the correct user or the events are not correct for user
    }

解决方案

Here is how I solved the issue. Hopefully it will help someone else. There may be some typos... this is just meant to show general idea. I called my GetData method recursively:

    //  When page loads
    $(document).ready(function () {
        FunctionToBegin();
    });


    // Populates params and call method containing AJAX call
    function FunctionToBegin() {
        // Populate any required params here, including the first param required for the first AJAX call

        // The following block uses the jQuery.Deferred() object, introduced in jQuery 1.5
        // See http://api.jquery.com/category/deferred-object/
        // the object allows us to chain callbacks, **in the order specified**

        // Get date range
        $.when(GetStartDate(), GetEndDate())
            .then(function () {
      var $trCurrent = $('.DataRow:first');
                //Pass in first userID
                GetData($trCurrent.find('td:first').text().trim()); 
            })
                .fail(function () {
                    failureAlertMsg();
                }
           )
    }


    function GetData(userID) {
        // get the user id
        UserId = userID;
        // Create a json string containing data needed to retrieve the required data
        jsonTextStringified = null;
        jsonTextStringified = JSON.stringify({ UserId: UserId, startDate: startDate, endDate: endDate, AdditionalValues: AdditionalValues });
        // Ajax call to web method, passing in string
        $.ajax({
            type: "POST",
            url: "/URL/default.aspx/WebMethod",
            data: jsonTextStringified,
            contentType: "application/json",
            dataType: "json",
            async: true,
            success: SuccessFunction,
            error: function (d) { alert('Failed' + d.responseText + '\nPlease refresh page to try again or contact administrator'); }
        });
    }

    function SuccessFunction(data) {
      if (data != null && data.d != null && data.d.Temp != null) {
    // Do useful stuff


    // Process next user id
            nextUserID = SomeMethod();
            if (nextUserID != 0) { GetData(nextUserID) }
        }
        else {
                 nextUserID = SomeMethod();
                 if (nextUserID != 0) {  GetData(nextUserID) }
            }
        }
    }

This general outline permits each async call to complete before processing the next call. In other words, the group of async calls don't execute all at once and thus, don't hammer the web method responsible for returning data. In my case, I was returning a dataset containing two tables and the tables returned were inconsistently accurate unless I set the async flag to false (not acceptable for my purpose), or followed the oulined approach.

这篇关于有没有一种方法,以确保后续调用执行之前的第一个AJAX调用完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆