使用延迟与jQuery Ajax调用,并与用户确认之间的阅读沿异步流程 [英] Using deferred with jquery ajax calls and async processes along with user confirmation reading in between

查看:180
本文介绍了使用延迟与jQuery Ajax调用,并与用户确认之间的阅读沿异步流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景结果
这是在延续我的问题<一href=\"http://stackoverflow.com/questions/10717982/correct-way-to-set-up-a-sequence-of-synchronous-asynchronous-functions-all-of-wh\">Correct方法设置的同步/异步函数序列所有这一切都可以停止表单提交和进一步处理?

我对什么是正确的方法(延迟管道)的答案,但我仍然不能够真正实现这一点。我刚开始今天的jQuery递延API读书,我无法掌握的还不很多。 jQuery的API单证似乎与小例子太复杂了。任何人都可以把链接,对此一些基本的演示/教程?我在这里需要一个脚踏启动。

I got the answer on what was the correct way (deferred pipe), but I am still not able to actually implement this. I just started reading on jquery deferred API today and I could not grasp much yet. The jQuery API documentations seem too complicated with little example. Could anyone put links to some basic demos/tutorials regarding this? I need a kick-start here.

详情结果
我有jQuery的1.6版在这个项目中使用。

Details
I have jquery version 1.6 being used in this project.

考虑这个例子 -
当用户点击提交表单按钮 - 结果
1.运行validateInventory()。结果
   一个。如果验证失败,显示一个确认对话框用户,如果用户同意(请转到步骤2)结果
   或结果
   湾如果验证通过(转到步骤2)结果
2.运行preValidateUrls()。结果
   一个。如果验证失败,显示一个确认对话框用户,如果用户同意(转到步骤3)结果
   或结果
   湾如果验证通过(转到步骤3)结果
3.提交表单。

Consider this example - When user clicks form submit button -
1. Run validateInventory().
a. If validation fails, display a confirmation dialog to user, if user agrees (go to step 2)
Or
b. If validation passes (go to step 2)
2. run preValidateUrls().
a. If validation fails, display a confirmation dialog to user, if user agrees (go to step 3)
Or
b. If validation passes (go to step 3)
3. Submit the form.

以下是我有异步函数的结构 -

Following is the structure of the asynchronous functions that I have -

注意,这个功能也有内部如果(确认)模块。阅读我的问题2

    function validateInventory()
    {
         $.ajax({
           type: "POST",
           url: posturl+"?"+params,
           dataType: "json",
           success: function(res)
               { 
                     if(!res.success)
                     {
                          //display some confirmation dialog, if user agrees con
                          if(confirm(msg)) 
                          {
                                //continue with next validation step 
                          }
                     }  
                     else
                     {
                          //validation success - so continue with next validation step
                     }  
                }
            });
    }

    //similar logic as inside validateInventory()
    function preValidateUrls()
    {


    }

我还可以具有在验证逻辑一些同步验证函数(客户端仅逻辑),在该序列的任何地方 -

I may also have some synchronous validation function (client-side-only logic) in the validation logic, anywhere in the sequence -

function syncVal()
{
    return true/false
}

问题1 应该把这样的功能也语法类似于异步函数?

Question 1 Should the syntax for putting such functions also be similar to the asynchronous functions?

问题2 仅在用户确认如何处理显示(如果验证失败)确认对话框的显示,并继续下一验证步骤。如果有功能的一些调整?在如果(确认)块需要被外界感动?

Question 2 How do I handle the display of showing confirmation dialog (if validation fails) and proceed to next validation step only if user confirms. Should there be some restructuring of the function? The if(confirm) block needs to be moved outside?

我在哪里已经达到了迄今为​​止

好了没有什么,我想我需要使用。当 .done 的API。

Well nothing much, I guess I need to use .when, .done APIs.

推荐答案

如果我理解的步骤1,2,3正确的话,那么你要能codeD像这样的逻辑:

If I understand Steps 1,2,3 correctly, then the logic you want can be coded something like this :

$(function() {
    function validateInventory(form) {//`form` is passed conventionally at the left hand end of the pipe chain.
        var dfrd = $.Deferred();//A Deferred object to be resolved/rejected in response to ajax success/error.
        var params = .....;//use values from `form` as required
        $.ajax({
            type: "POST",
            url: posturl + "?" + params,
            dataType: "json"
        }).done(function(res) {//ajax success
            if(res.success || confirm(msg1)) { dfrd.resolve(form); }//Here we resolve dfrd, passing `form` in order to make `form` available to the next function in the pipe chain.
            else { dfrd.reject("validateInventory() failed (not verified)"); }//Application error. By rejecting with a specific message, we have the means of knowing where the failure occurred.
        }).fail(function(jqXHR, textStatus, errorThrown) {//ajax error
            dfrd.reject("validateInventory() failed (textStatus)");//Again, a specific message.
        });
        return dfrd;
    }

    //Similar logic as inside validateInventory()
    function preValidateUrls(form) {//The form, is piped through by the statement `dfrd.resolve(form);` in validateInventory
        var dfrd = $.Deferred();
        var params = .....;
        $.ajax({
            type: "POST",
            url: posturl + "?" + params,
            dataType: "json"
        }).done(function(res) {
            if(res.success || confirm(msg2)) { dfrd.resolve(form); }
            else { dfrd.reject("preValidateUrls() failed (not verified)"); }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            dfrd.reject("preValidateUrls() failed (textStatus)");
        });
        return dfrd;
    }

    //This is the function to be called if the various stages of validation were successful.
    function overallSuccess(form) {
        form.submit(); 
    }

    //This is a common error handler, which will be called if either of the validation stages fail.
    function errorHandler(message) {
        alert(message);//or whatever
    }

    var myForm = $("form").get(0);//for example

    //And now the glue that puts the component parts together.
    validateInventory(myForm).pipe(preValidateUrls, errorHandler).pipe(overallSuccess, errorHandler);
});

未经检验

有关说明,请参见code注释。

For explanation, see comments in code.

整个事情可以分解任何数目的不同方式。我会选择code它上面的,因为零部件是独立的和明确的,而胶水的声明(管链)是非常简洁,易于扩展,以适应进一步的验证步骤。与其他方法,你会得到的功能深度嵌套这是很难效仿,尤其是对人谁也保持在未来code。

The whole thing can be factored any number of different ways. I would choose to code it as above because the component parts are separate and clear, and the "glue" statement (the pipe chain) is very concise and easy to extend to accommodate further validation steps. With other approaches, you tend to get deep nesting of functions which is hard to follow, especially for someone who has to maintain the code in the future.

这篇关于使用延迟与jQuery Ajax调用,并与用户确认之间的阅读沿异步流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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