【问题标题】:Page refresh after the request is Done请求完成后页面刷新
【发布时间】:2013-12-12 20:49:30
【问题描述】:

我有一个带有许多复选框的页面,我编写了一个 JS 代码,为每个页面调用 PHP 页面,我想在调用完成后刷新页面.. 这是我的代码

$(".matchFrnds").each(function(){  //For each CheckBox

        if($(this).is(':checked')){

            var sendData= $(this).val();

             $.post('Call to PHP Page',{sendData:sendData},function(data){


            window.location.reload();
                });
        }
        });

问题是页面在完成几个复选框后重新加载,所以如果有 60 个复选框,页面在调用 10 个复选框后重新加载。我还更改了window.location.reload(); 的位置,但结果是一样的,我希望在完成对所有复选框的调用后重新加载。

【问题讨论】:

  • 你为什么要使用 ajax 来执行页面重新加载,这意味着不重新加载页面?带有提交的普通表单不够好吗?
  • 你必须设置一些标志来检查所有选择框是否被选中
  • @STTLCU 我同意你的观点,但我想在 ajax 上进行透明的 PHP 处理,然后重新加载/或者可能只是更新 div。但在每种情况下,我都需要知道请求何时完成

标签: javascript php jquery checkbox window.location


【解决方案1】:

您可以查看已完成的通话次数,然后重新加载

var boxes = $(".matchFrnds:checked").length;
var calls = 0;
$(".matchFrnds").each(function(){  //For each CheckBox
        if($(this).is(':checked')){
            var sendData= $(this).val();    
            $.post('Call to PHP Page',{sendData:sendData},function(data){

               calls++; 
               if(calls >= boxes) {    
                 window.location.reload();
               }

            });
        }
  });

【讨论】:

  • (".matchFrnds:checked").length;返回不同于 $(".matchFrnds:checked").length; 的数字
  • 长度怎么不一样?
  • 我错过了$ :)。是你想要的答案吗?
  • yaa.. 没有 $ 它只是一个字符串 "abcd".length //4
【解决方案2】:

真的很简单。
您只需要设置一个计数器,然后在最后一个上调用reload()。
这个想法是有另一个变量......

// Save the element to iterate in a variable
var matchFrnds = $(".matchFrnds"),
    //and save its length too
    length = matchFrnds.length;

//Iterate over it
matchFrnds.each(function() {
    // modify the counter
    --length;
    if ($(this).is(":checked")) {
        // do your things
        $.post( ... , function(data) {
            //do what you need to do with the data...
            // ....
            // ....
        });
    }
    //and, if it's the last element
    if (!length) {
        // LAST ITERATION!
        window.location.reload();
    }
});

就是这样。

【讨论】:

  • 如果你把 relaod 放在 callback 之外,relaod 将在最后一个 ajax 调用完成之前调用
  • 你是对的,但是如果我把它放在里面,如果最后一个复选框没有被选中,重新加载将永远不会发生。我想问题作者会弄清楚这一点并实施相应的条件以使其正常工作。无论如何,我应该改变它吗?
【解决方案3】:

您可以使用 .ajaxStop-Event

http://api.jquery.com/ajaxStop/

【讨论】:

  • 任何细节,他为什么要停止ajax?
【解决方案4】:

您可以在完成请求后尝试:

location.reload();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    相关资源
    最近更新 更多