【问题标题】:HTML button to load data and refresh UI用于加载数据和刷新 UI 的 HTML 按钮
【发布时间】:2014-08-01 11:27:47
【问题描述】:

这里的情况:

在我的 html 页面中,我有一个链接,onclick 运行一个 PHP 脚本。

<iframe style="display:none;" name="target"></iframe>

<a href="path/to/my/script.php" target="target">Load new tasks</a>

我使用不可见的 iframe 来执行脚本,但我停留在同一页面上。

此链接执行script.php 更新mysql 数据库,但为了看到新内容必须重新加载页面。

当然,我总是可以创建一个单独的按钮/链接来重新加载当前页面。

但我想知道是否有一种方法可以执行 PHP 脚本并使用一个 html 按钮重新加载当前页面。

【问题讨论】:

  • 肯定有,它叫做 Ajax。
  • 使用 Ajax+Jquery 实现你的目标..
  • 你应该为此使用 ajax
  • 我认为 OP 明白了 ;)
  • 在这种情况下你真的不需要 AJAX。如果您确实希望页面重新加载,为什么需要隐藏的 iframe 来执行?您可以发布整个页面,该页面将运行您的 PHP 脚本并一次性重新加载页面

标签: javascript php html button


【解决方案1】:

最好这样使用:

1:使用通用的Javascript框架,例如JQuery

2:为您的内容创建链接和 Div:

<a href="#" id="reload">Update my Data and reload my new Content</a>
<div id="result"></div>

3:使用Jquery给你的链接添加点击事件:

$('#reload').click(function(e) {
    // Prevent from going to the link provided in href
    e.preventDefault();

    // make POST Request to script

    $.post( "myScriptHandler.php", { value1: "1", value2: "2" })
    .done(function( data ) {

        // if done, refresh my Div with html content from your PHP Script
        $('#result').html('')
        $('#result').load('mydata.php');


    });

}

【讨论】:

    【解决方案2】:

    您不需要 AJAx - 只需将脚本返回到更新顶层页面的 iframe...

    <?php
    
    ....
    $new=run_updates();
    print "<div id='newcontent'>$new</div>\n";
    ?>
    <script>
    var dest=parent.document.getElementById('oldcontent');
    var src=document.getElementById('newcontent');
    dest.innerHTML=src.innerHTML;
    </script>
    

    (未测试,YMMV)

    【讨论】:

      【解决方案3】:

      我将向您展示如何在这种情况下使用 Ajax:

      这是你的 html 和 js 代码:

      <script type="text/javascript">
        $(".link").on("click", function() {
          $.ajax({
            url: "your_php_script.php",
            dataType: "json",
            cache: false,
            success: function(data) {
              location.reload(true);    
            }
          });
        });
      </script>
      
      <html>
        <body>
          <a class="link" target="target">Load new tasks</a>
        </body>
      </html>
      

      当你点击'a'标签时,jQuery Ajax 脚本会调用你的 php 脚本,当它返回成功时,你的页面会被刷新。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 2019-03-05
        • 2016-09-29
        相关资源
        最近更新 更多