jQuery向导步骤在Ajax调用完成之前移动

21

根据一些ajax调用的结果,我如何控制移动到下一步?data.d返回一个布尔值。

$("#wizard").steps({
            onStepChanging: function (event, currentIndex, newIndex) {
                var move = false;
                if (currentIndex == 2) {
                    move = false;
                    $.ajax({
                        type: 'POST',
                        url: "Reservation.aspx/SomeFunction",
                        data: serializeData({  }),
                        contentType: "application/json",
                        dataType: 'json',
                        success: function (data) {
                            move = data.d;
                            return true;
                        },
                        error: ajaxLoadError
                    });
                }
                return move;
            },
            saveState: true

        });

我没有使用过jquery向导步骤,但你的问题发生是因为ajax被异步调用。请查看另一个接受ajax加载的向导插件(例如:https://github.com/mstratman/jQuery-Smart-Wizard)。 - Gasim
11个回答

8
$.ajax({
    type: 'POST',
    url: "Reservation.aspx/SomeFunction",
    async: false,
    contentType: "application/json",
    dataType: 'json',
    success: function (data) {
       move = data.d;
       return true;
    },
    error: ajaxLoadError
});

似乎没有办法使其异步工作,因此我将向您授予奖金,因为这是我发现的唯一使其工作的方法。 - Manolo
使用同步方式非常糟糕,因为它会冻结用户界面。实际上,可以使用延迟对象来解决这个问题。请查看此链接:https://github.com/rstaib/jquery-steps/pull/232 - undefined

8

我遇到了同样的问题,甚至考虑使用“setStep”来强制ajax加载后的步骤,然而jquery.steps的最新版本已经取消了“setStep”...

最终,我使用了“next”方法,并不得不使用全局触发器来停止onChanging事件的无限循环。简单来说,如果ajax返回有效数据,我就强制向导进入下一个步骤; 否则,它将留在当前步骤,以下是代码:

var $stopChanging = false; 

.... ....

onStepChanging: function (event, currentIndex, newIndex) {
      if ($stopChanging) {
        return true;
      } else {
        items = $.ajax({
        type: 'POST',
        url: "Reservation.aspx/SomeFunction",
        data: serializeData({  }),
        contentType: "application/json",
        dataType: 'json',
        success: function (data) {
            $stopChanging = true;
            wizard.steps("next");
        },
        error: ajaxLoadError
    });
   },
   onContentLoaded: function (event, currentIndex) {
       $stopChanging = false;
   }
}

逻辑如下:
  1. 点击“下一步”按钮触发onStepChanging事件
  2. 默认情况下,jquery.steps onStepChanging事件返回false,然后调用$.ajax,如果它返回有效数据(成功),则调用jquery.steps跳转到下一步,onStepChanging再次触发,如果无效,则不做任何事情,停留在当前步骤
每次触发两个onStepChanging事件并不是一个好主意,但目前只能这样。
您可能需要为不同的步骤索引行为添加更多条件。

这似乎不是一个完整的答案。 - RBT
伙计们,这是真正可行的答案,没有其他的了。我花了两天时间才找到这个答案,感谢你,避免了每次都创建无限循环所浪费的时间...... - MR_AMDEV

5

您可以使用Samy的方法来进行同步的ajax请求。

$("#wizard").steps({
    onStepChanging: function (event, currentIndex, newIndex) {
        if (currentIndex == 2) {
            var requestResult = $.ajax({
                type: 'POST',
                url: "Reservation.aspx/SomeFunction",
                async: false,
                contentType: "application/json",
                dataType: 'json',
                error: ajaxLoadError
            });
            return requestResult.responseJSON.Result == "/*your expected value*/"
        }
    },
    saveState: true
});

4
如果您不希望$.ajax()函数立即返回,请将async选项设置为false:
如果您的ajax调用没有服务器响应,则为Ajax设置超时,然后它会继续下一个进程。
$("#wizard").steps({
            onStepChanging: function (event, currentIndex, newIndex) {
                var move = false;
                if (currentIndex == 2) {
                    move = false;
                    $.ajax({
                        type: 'POST',
                        url: "Reservation.aspx/SomeFunction",
                        data: serializeData({  }),
                        contentType: "application/json",
                        dataType: 'json',
                        async: false,
                        cache: false,
                        timeout: 30000,
                        success: function (data) {
                            move = data.d;
                            return true;
                        },
                        error: ajaxLoadError
                    });
                }
                return move;
            },
            saveState: true

        });

正如我所说,“我想知道是否有任何异步方法”。 - Manolo
是的,我看过那个了,但是我忘了提到如果没有使用异步(ASYNC),处理会非常困难。虽然可以使用setTimeout(function () { " Your AJAX Code" }, 1000);实现,但这不是一种安全的处理方式。如果您对ASYNC没有任何问题,上述解决方案是安全和可靠的。 - Nirav Patel
你从上面的答案得到帮助了吗? - Nirav Patel
不,这是我的实际方法。我正在寻找一种异步的方法。但是,我不确定是否可以在这个插件中实现。如果不行,我将继续将“async”设置为“false”。无论如何,赏金是为了异步方法。 - Manolo
看看@Samy的回答。他基本上和你回答的一样。 - Manolo
显示剩余2条评论

3
我找到了另一种解决这个问题的方法。OnStepChanging 只支持 boolean 类型。有一个拉取请求#232,它添加了对延迟对象的使用。(我在GitHub上也找到了如何使用延迟对象的方法)。我将这个修改后的版本包含在我的项目中,并在OnStepChanging中像这样使用:
    var def = $.Deferred();

    $.ajax({
        type: "POST",
        url: url,
        //async: false,
        beforeSend: function (xhr) {
            //ASP CORE Antiforgery token
            xhr.setRequestHeader("RequestVerificationToken",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        failure: function (xhr) {
            failureCallback(xhr);
        }
    }).done(function (response) {
        //Result of server validation
        var responseResult = response.result === "Success" ? true : false;
        // Check response
        def.resolve(responseResult);
        }).fail(function (response) {
            console.log(response);
            return false;
        });

    return def; // This is the Deferred that should be returned and NOT the one from jQuery Ajax

我希望这能对其他人有所帮助。:-)

2

在多次尝试后,这是我唯一能够使其工作的方式,这就是@joe-lu上面所说的。你只需要启动异步调用并返回false。这将使向导保持在同一步骤上。然后,在成功处理程序中,你可以通过编程方式移动到下一步。

$("#wizard").steps({
            onStepChanging: function (event, currentIndex, newIndex) {
                if (currentIndex == 2) {
                    //Would be a good idea to start a spinner here!
                    //would be a good idea to disable next button here!
                    $.ajax({
                        type: 'POST',
                        url: "Reservation.aspx/SomeFunction",
                        data: serializeData({  }),
                        contentType: "application/json",
                        dataType: 'json',
                        success: function (data) {
                            //stop spinner here!
                            //programmatically move to next step on success.
                            $("#wizard").steps("next");
                        },
                        error: ajaxLoadError
                    });
                }
                //Prevents natural movement to next step.
                //will be done programmatically
                return false;
            },
            saveState: true
        });

2
$("#wizard").steps({
        onStepChanging: function (event, currentIndex, newIndex) {
            var $out= false;
            if (currentIndex == 2) {
                $out= false;
                $.ajax({
                    type: 'POST',
                    url: "Reservation.aspx/SomeFunction",
                    data: serializeData({  }),
                    contentType: "application/json",
                    dataType: 'json',
                    success: function (data) {
                        move = data.d;

                        $out = true;
                    },
                    error: ajaxLoadError
                });
            }
            return $out;
        },
        saveState: true

    });

将全局变量 $out 放入其中!


2

我遇到了类似的问题,但是我在使用 parsleyjs 进行验证。你可以从我的代码中得到一些想法。

我的代码如下:

             onStepChanging: function (event, currentIndex, newIndex) {

                 // ======== Code that fails 

                 //var step = $wizard_advanced.find('.body.current').attr('data-step'),
                 //$current_step = $('.body[data-step=\"'+ step +'\"]');                        


                // check input fields for errors
                //$current_step.find('[data-parsley-id]').each(function() {
                    //this adds .md-input-danger to inputs if invalid
                    //there is remote validation occurring here via ajax
                    // async: false
                    //$(this).parsley().validate();
                //});

                // this is executed before ajax validation is finished 
                //return $current_step.find('.md-input-danger').length ? false : true;

                // ======== END of Code that fails 

                // FIX
                // waits on ajax validation to finish before returning
                if( $wizard_advanced_form.parsley().validate() ) {
                    return true;
                } else {
                    return false;
                }
                //FIX                    
            }

2
var items;

$("#wizard").steps({
onStepChanging: function (event, currentIndex, newIndex) {
    var move = false;
    if (currentIndex == 2) {
        move = false;

        items = $.ajax({
            type: 'POST',
            url: "Reservation.aspx/SomeFunction",
            data: serializeData({  }),
            contentType: "application/json",
            dataType: 'json',
            success: function (data) {
                move = data.d;
                return true;
            },
            error: ajaxLoadError
        });


    }
    return move;
},
saveState: true

});



items.success(function (data) {
//if can log in go to logged in page
if (data.success == true) {
    alert("Working");
    var move = data.d;
    return true;

} else {
    alert("didnt work");
}
// output of data
alert(JSON.stringify(data));
});

1
var is_async_step = false;
$("#wizard").steps({
        onStepChanging: function (event, currentIndex, newIndex) {
            //USED TO SEND USER TO NEXT STEP IS ASYNC REQUEST IS PRESENT - FOR AJAX CALL 
            if (is_async_step) {
                is_async_step = false;
                //ALLOW NEXT STEP
                return true;
            }

            if (currentIndex == 2) {                
                $.ajax({
                    type: 'POST',
                    url: "Reservation.aspx/SomeFunction",
                    data: serializeData({  }),
                    contentType: "application/json",
                    dataType: 'json',
                    success: function (data) {
                        move = data.d;

                        //Add below 2 lines for every Index(Steps).                            
                        is_async_step = true;
                        //This will move to next step.
                        $(form).steps("next");
                    },
                    error: ajaxLoadError
                });
            }
             //Return false to avoid to move to next step
             return false;
        },
        saveState: true
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接