可以这样不同步的AJAX做了什么? [英] Can this be done without synchronous AJAX?

查看:98
本文介绍了可以这样不同步的AJAX做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从同步改变我的下code以异步AJAX性能的原因。 这可能吗? 我发现,几乎所有我的AJAX调用是同步的,所以我感觉到我失去了一个设计模式。一般情况下,如果你需要显示的数据从服务器返回的,那么就不要你需要等待(异步:假的)?服务器与数据作出响应,然后才能继续

在下面的code,元素a.popup'绑定了两个点击处理程序。第一个是一个夹(未示出),第二个是如下所示的code。我想这样做并没有异步:假,但它不工作。

 函数completed_investment($输入){

        VAR的结果;

        jQuery.ajax({
            键入:POST,
            网址:'/ AJAX / completed_investment',
            数据类型:JSON,
            数据:$输入,
            异步:假的,//需要等到获取结果。
            成功:功能(数据){
                结果=数据;
            }
        });
        返回结果;
}


// AJAX  - 完成
jQuery的('a.open,弹出)。点击(函数(){
    变量$父= jQuery的(本).parent();
    变量$ InvestmentID = $ parent.siblings('输入')ATTR('值')。
    变量$投入;
    变种$输出;

    $输入= {'InvestmentID:$ InvestmentID};
    $输出= completed_investment($输入);

    //如果一个投资完成,更新HTML
    如果($ outputs.state =='开始')
    {

        $ parent.siblings('计划,味精')删除()。
        $ parent.removeClass(完成按钮)
                    .addClass(加-INV-按钮)
                    html的(+添加到您的计划);
        $ newpoints ='(++ $ outputs.points ++ $ outputs.plural +);
        parent.siblings $('做点')。removeClass移除('做点')
                                        .addClass(加点)
                                        html的($ newpoints);
    }
});
 

解决方案

您的直觉是正确的:不做同步AJAX 相反,把code表示预期的结果。 成功的回调!

 的jQuery(a.open,弹出)。点击(函数(){
    变量$父= jQuery的(本).parent();
    变量$ InvestmentID = $ parent.siblings('输入')ATTR('值')。
    变量$投入;
    变种$输出;

    $输入= {'InvestmentID:$ InvestmentID};
    $输出= completed_investment($输入功能($输出){
      如果($ outputs.state =='开始')
        {

          $ parent.siblings('计划,味精')删除()。
          $ parent.removeClass(完成按钮)
                .addClass(加-INV-按钮)
                html的(+添加到您的计划);
          $ newpoints ='(++ $ outputs.points ++ $ outputs.plural +);
          parent.siblings $('做点')。removeClass移除('做点')
                                    .addClass(加点)
                                    html的($ newpoints);
         }
    });
 

然后改变功能,使AJAX调用:

 函数completed_investment($输入,whenFinished){

    VAR的结果;

    jQuery.ajax({
        键入:POST,
        网址:'/ AJAX / completed_investment',
        数据类型:JSON,
        数据:$输入,
        异步:假的,//需要等到获取结果。
        成功:功能(数据){
            whenFinished(数据);
        }
    });
}
 

在JavaScript中的基本思路是,因为它的那么容易只是包裹在一个匿名函数一些code上下左右折腾吧,有没有必要有code等待为你描述。相反,您只需打包的工作,并把它交给了服务功能用作事件处理程序。当HTTP请求完成,即发生触发事件,你的处理程序被调用。因为在JavaScript中的作用域规则的,可到code中的局部变量仍然可以按照它们被设置为在处理函数传递到了AJAX机制。

I'd like to change my following code from synchronous to async AJAX for performance reasons. Is this possible? I'm finding that almost all of my AJAX calls are synchronous, so I sense that I'm missing a design pattern. In general, if you need to display data that is returned from the server, then don't you need to wait (async: false) for the server to respond with data before you can continue?

In the code below, the element 'a.popup' has two 'click' handlers bound to it. The first is a lightbox (not shown) and the second is the code shown below. I tried doing this without "async: false", but it doesn't work.

function completed_investment($inputs) {

        var result;

        jQuery.ajax({
            type: 'POST',
            url: '/ajax/completed_investment',
            dataType: 'json',
            data: $inputs,
            async: false,          // need to wait until get result.
            success: function(data) {
                result = data;
            }
        });
        return result;
}


// AJAX - Completed
jQuery('a.open-popup').click(function(){
    var $parent = jQuery(this).parent();
    var $InvestmentID = $parent.siblings('input').attr('value');
    var $inputs;
    var $outputs;

    $inputs = { 'InvestmentID' : $InvestmentID };
    $outputs = completed_investment($inputs);

    // If an investment was completed, update HTML
    if ($outputs.state == 'Begin')
    {

        $parent.siblings('.plan-msg').remove();
        $parent.removeClass('completed-button')
                    .addClass('add-inv-button ')
                    .html('+ Add to Your Plan');
        $newpoints = '(+' + $outputs.points + " " + $outputs.plural + ")";
        $parent.siblings('.done-points').removeClass('done-points')
                                        .addClass('add-points')
                                        .html($newpoints);
    }
});

解决方案

Your instincts are correct: don't do synchronous AJAX. Instead, put the code that expects the "result" inside the "success" callback!

jQuery('a.open-popup').click(function(){
    var $parent = jQuery(this).parent();
    var $InvestmentID = $parent.siblings('input').attr('value');
    var $inputs;
    var $outputs;

    $inputs = { 'InvestmentID' : $InvestmentID };
    $outputs = completed_investment($inputs, function($outputs) {
      if ($outputs.state == 'Begin')
        {

          $parent.siblings('.plan-msg').remove();
          $parent.removeClass('completed-button')
                .addClass('add-inv-button ')
                .html('+ Add to Your Plan');
          $newpoints = '(+' + $outputs.points + " " + $outputs.plural + ")";
          $parent.siblings('.done-points').removeClass('done-points')
                                    .addClass('add-points')
                                    .html($newpoints);
         }
    });

Then change the function that makes the AJAX call:

function completed_investment($inputs, whenFinished) {

    var result;

    jQuery.ajax({
        type: 'POST',
        url: '/ajax/completed_investment',
        dataType: 'json',
        data: $inputs,
        async: false,          // need to wait until get result.
        success: function(data) {
            whenFinished(data);
        }
    });
}

The basic idea in JavaScript is that since it's so easy to just wrap some code up in an anonymous function and toss it around, there's no need to have code "wait" as you describe. Instead, you simply package up the work and hand it over to the service function for use as an event handler. When the HTTP request finishes, that occurrence will trigger the event, and your handler is called. Because of the scoping rules in JavaScript, the local variables available to your code are still available exactly as they were set when the handler function was passed in to the AJAX mechanism.

这篇关于可以这样不同步的AJAX做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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