【问题标题】:Limit page reload on ajax call with GET request使用 GET 请求限制 ajax 调用的页面重新加载
【发布时间】:2015-10-28 07:07:59
【问题描述】:

在我的应用程序中,如果 URL 具有某些 $_GET 参数,我想在此 AJAX 更新后更新会话并重新加载页面,以下是我的代码。

if($_GET['something']){
   //do something
   $.ajax({
            type: "POST",
            url: "localhost/example/ajaxpage.php",
            data: {
                foo: foo_test,
                bar: bar_test,
            },
            success: function (data) {
                window.location.reload();
            }
        });
}

但在页面重新加载时它会再次获得 $_GET,因此页面正在重复重新加载。如何解决此问题,以便在 AJAX 更新后页面仅重新加载一次。

【问题讨论】:

  • 取消设置 $_GET['something'] 的值
  • 使用 window.location.href 而不是重新加载并传递不带查询参数的 URL

标签: php jquery ajax


【解决方案1】:

替换

window.location.reload();

window.location.href = window.location.origin; 或在此处使用精确的URL

【讨论】:

    【解决方案2】:

    您可以在 window.location.href 中指定 URL,而不是 relaoad()

    if($_GET['something']){
       //do something
       $.ajax({
                type: "POST",
                url: "<?= $HOMEPAGE_ROOT; ?>/example/ajaxpage.php",
                data: {
                    foo: foo_test,
                    bar: bar_test,
                    action: 'reload'
                },
                success: function (data) {
                    window.location.href = window.location.origin;
                }
            });
    }
    

    这里你可以使用window.location.origin或者你自己的url,其中something不是get参数。

    【讨论】:

      【解决方案3】:

      与该会话变量一起检查,如下所示:

      if($_GET['something'] && isset($_SESSION['test']))
      

      或与会话的价值。

      【讨论】:

        【解决方案4】:

        使用下面的代码

               <?php 
                if($_GET['something'] & !isset($_GET['flag'])){
                ?>
                    <script>
                   //do something
                   $.ajax({
                            type: "POST",
                            url: "localhost/example/ajaxpage.php",
                            data: {
                                foo: foo_test,
                                bar: bar_test,
                            },
                            success: function (data) {
        
                                window.location.href ="Your Url"?something=xyz&flag=1; 
                            }
                        });
                    </script>
                    <?php 
                }
                ?>
        

        【讨论】:

          最近更新 更多