uery中的JavaScript函数foreach循环不等待响应

uery中的JavaScript函数foreach循环不等待响应

本文介绍了jQuery中的JavaScript函数foreach循环不等待响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的foreach循环:

  jQuery(。custom-checkbox)。each(function(){$ b $如果(jQuery(this).attr('data-action')=='true'){

if(deleteQuoteItemFromListing(jQuery(this).attr('data-id'))) {
console.log('passed');
} else {
console.log('failed');
}
}
}) ;

这个函数是(它使用原型),但是成功了

 函数deleteQuoteItemFromListing(id){
//做一些操作并成功
delurl = getDelUrl()+ id; // baseurl / module / action / delete / id
new Ajax.Request(delurl,{
method:'get',
onSuccess:function(transport){
return TRUE ;
}
})
}

但问题是所有foreach立即执行,不等待函数的响应。它会打印失败,即使操作成功了。

更新



另一种方法我先试一下是这个

  jQuery('。delete-from ()函数(){
var i = 0,j = 0;
jQuery(。custom-checkbox)。 jQuery(this).attr('data-action')=='true'){
i ++;
}
});


(i == 0){
alert('请选择产品');
return false;
}

jQuery(。custom-checkbox) .each(function(){

if(jQuery(this).attr('data-action')=='true'){

var urlData =< ;'php echo $ this-> getUrl('qquoteadv / index / delete /');?>;
urlData + =id /+ jQuery(this).attr('data-id' )+/

var ajax = jQuery.ajax({
类型:GET,
url:urlData,
成功:函数(msg){
j ++;



$ b if(i == j){location.reload();} //完成后,重新加载页面
});
});

问题是要知道所有操作完成并重新加载页面。我的猜测是,你省略的代码正在做一个异步的Ajax调用。由于ajax在默认情况下是异步的,所以你写的代码( $ .ajax 或其他)开始进程,但是这个过程继续在你的代码继续运行的情况下。



没有合理的方法使 deleteQuoteItemFromListing 函数 wait 的回应。 (虽然有可能做到同步ajax,但是它通过锁定浏览器UI来增加用户体验)B)jQuery会在某个阶段删除这个选项,迫使你直接去到XHR,如果你想继续这样做)。相反,重构你的代码,以包容Web编程的异步性,通过让你的函数返回一个承诺或接受回调,然后解决承诺或完成时调用回调。

以下是承诺版本的一个粗略的概念:

  jQuery(。custom-checkbox)。each(function(){
if(jQuery(this).attr('data-action' )(
deleteQuoteItemFromListing(jQuery(this).attr('data-id'))
.done(function(id){
console.log(id + (传递));
})
.fail(函数(id){
console.log(id +'failed');
} );
}
});

函数deleteQuoteItemFromListing(id){
var d = jQuery.Deferred();
jQuery.ajax(/*...*/)
.done(function(){//如果
d.resolveWith(id); // ajax调用工作,如果
})// ajax调用失败失败;如果改为ajax
.fail(function(){//调用总是有效并返回一个标志,
d.rejectWith(id); //相应地调整
});
return d.promise();
}


My foreach loop:

jQuery(".custom-checkbox").each(function() {
      if (jQuery(this).attr('data-action') == 'true') {

      if(deleteQuoteItemFromListing(jQuery(this).attr('data-id'))){
                    console.log('passed');
            }else{
                    console.log('failed');
            }
      }
 });

And the function is(It's using prototype) but it successes

function deleteQuoteItemFromListing(id){
    //does someoperations and on success
    delurl = getDelUrl()+id; //baseurl/module/action/delete/id
    new Ajax.Request(delurl,{
        method: 'get',
        onSuccess: function(transport){
            return TRUE;
        }
    })
}

but the problem is all foreach executes at once, and doesn't wait for response from function. It prints failed even the operation is success.

Updated

The other way round i tried first is this

jQuery('.delete-from-quote').click(function() {
        var i = 0, j = 0;
        jQuery(".custom-checkbox").each(function() {
            if (jQuery(this).attr('data-action') == 'true') {
                i++;
            }
        });


        if (i == 0) {
            alert('please choose product');
            return false;
        }

        jQuery(".custom-checkbox").each(function() {

            if (jQuery(this).attr('data-action') == 'true') {

                var urlData = "<?php echo $this->getUrl('qquoteadv/index/delete/'); ?>";
                urlData += "id/" + jQuery(this).attr('data-id') + "/"

                var ajax = jQuery.ajax({
                    type: "GET",
                    url: urlData,
                    success: function(msg) {
                        j++;
                    }
                })

            }
          if(i==j){location.reload();} //after completing all, reload the page
        });
  });

The problem is to know all action completed and reloading the page.

解决方案

My guess is that the code you've omitted is doing an asynchronous ajax call. Since ajax is asynchronous by default, the code you write there ($.ajax or whatever) starts the process, but then the process continues in the background while your code continues to run.

There's no reasonable way to make the deleteQuoteItemFromListing function wait for the response. (While it's possible to do synchronous ajax, A) it makes for a poor user experience by locking up the browser UI, and B) jQuery will be removing that option at some stage, forcing you to go direct to XHR if you want to keep doing it.)

Instead, restructure your code to embrace the asynchronous nature of web programming by having your function either return a promise or accept a callback, and then resolve the promise or call the callback when done.

Here's a rough idea of what the promise version would look like:

jQuery(".custom-checkbox").each(function() {
    if (jQuery(this).attr('data-action') == 'true') {
        deleteQuoteItemFromListing(jQuery(this).attr('data-id'))
            .done(function(id) {
                console.log(id + ' passed');
            })
            .fail(function(id) {
                console.log(id + ' failed');
            });
    }
});

function deleteQuoteItemFromListing(id){
    var d = jQuery.Deferred();
    jQuery.ajax(/*...*/)
        .done(function() {      // This bit assumes the deletion worked if
            d.resolveWith(id);  // the ajax call worked, and failed if the
        })                      // ajax call failed; if instead the ajax
        .fail(function() {      // call always works and returns a flag,
            d.rejectWith(id);   // adjust accordingly
        });
    return d.promise();
}

这篇关于jQuery中的JavaScript函数foreach循环不等待响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 12:50