jQuery循环,只有最后一次ajax成功执行

Mat*_*att 1 jquery

因此,这是我的Chrome扩展程序[此处]的核心 [ jq是 jQuery.noConflict()] jq('.pam div .fbCurrentActionLink')返回Facebook上每个“ Poke”链接。它使用.each()遍历每个人(又名每个人的“戳”链接),成功后,它将文本“ Poke”替换为粗体和绿色的“ Poked”文本。

function execute()
{
        jq('.pam div .fbCurrentActionLink').each(function () {

        anc=jq(this)
        uid=anc.attr('ajaxify').match(/(\d+)/)[0]

        //ajax
                var post_form_id = jq('#post_form_id').val();
                var fb_dtsg = jq('input[name=fb_dtsg]').val();
                //use AJAX to submit poke, via their fb id
                jq.ajax({
                        type: 'POST',
                        url: 'ajax/poke.php?__a=1',
                        data: 'uid=' + uid + '&pokeback=1&post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&post_form_id_source=AsyncRequest',
                        beforeSend: function(xhr){
                                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
                        },
                        success: function(data, textStatus){
                                anc.html('<b style="color:green !important">Poked</b>');
                        }
                });

        //ajax
        });

}
Run Code Online (Sandbox Code Playgroud)

现在,问题是,有3个要返回的戳。它将仅对最后一个执行.html()。我不知道为什么。

Cor*_*son 5

我认为您遇到的问题是,当第一个ajax调用完成时,anc的值已被覆盖。触发成功事件后,anc等于上一次迭代的值。要解决此问题,必须停止覆盖值,或者在循环期间,必须将每个ajax调用与放置结果的元素绑定在一起。

要将ajax调用与dom元素绑定,您需要提供contextajax调用的define 。

尝试一下,我希望它能起作用...

      jq.ajax({
              type: 'POST',
              context: this,        //added line
              url: 'ajax/poke.php?__a=1',
              data: 'uid=' + uid + '&pokeback=1&post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&post_form_id_source=AsyncRequest',
              beforeSend: function(xhr){
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
              },
              success: function(data, textStatus){
                    $(this).html('<b style="color:green !important">Poked</b>');  
                    //changed to $(this) instead of anc
              }
      });
Run Code Online (Sandbox Code Playgroud)