【问题标题】:Close javascript popup after form submission & update parent page?表单提交和更新父页面后关闭javascript弹出窗口?
【发布时间】:2019-10-05 05:44:51
【问题描述】:

我有一个来自 index.ejs 的弹出窗口,名为 math.ejs。按下提交确定按钮后,我希望 math.ejs 弹出窗口关闭并在 index.ejs 上显示计算值。但是现在,当我按下提交按钮时,弹出窗口会转到 index.ejs 并在那里更新;它不关闭。它不会在普通的 index.ejs 浏览器页面上更新它。我必须刷新该页面才能更新。

这是我尝试过的代码:

<form class="" action="/index" method="post" name="mathform">
      <p>Value: <%= myValue %></p>
      <button class="btn btn-md" name="button" value="confirm" onclick="CloseAndRefresh();">Ok</button>
</form>

<script language="javascript">
      function CloseAndRefresh() {
      opener.location.reload(true);
      setTimeout(function() {
      window.close();
      }, 3000);
     }
</script>

我确信这会起作用,因为它告诉父窗口重新加载,我什至在弹出窗口关闭之前设置了一个计时器。感谢您的帮助!

【问题讨论】:

  • 当您单击提交按钮时,表单将被提交。所以页面导航到 /index 。您将不得不使用 ajax 发送 post 请求,收到响应后,请致电 CloseAndRefresh
  • @Shazvi 有没有我可以学习的简单教程?我以前从未使用过 Ajax。谢谢你的解释!

标签: javascript html node.js express


【解决方案1】:

这里有一些东西可以帮助您入门。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<form class="" action="/index" method="post" name="mathform" onsubmit="submitForm(event)">
      <p>Value: <%= myValue %></p>
      <button class="btn btn-md" name="button" value="confirm">Ok</button>
</form>

<script language="javascript">
    function submitForm(e) {
        e.preventDefault(); // Prevents the form from getting submitted and navigating to /index

        $.post("/index",{
            // add your post field values here
            field1: "value1",
            field2: "value2",   
        })
            .done(function(data){ // ajax request completed successfully
                CloseAndRefresh();
            })
            .fail(function(error) { // ajax request failed
                // TODO: handle error accordingly
                CloseAndRefresh();
            });
    }

    function CloseAndRefresh() {
        opener.location.reload(true);
        // this timeout can be removed since the page refresh has already started at this point
        setTimeout(function() {
            window.close();
        }, 3000);
    }
</script>

Ajax 请求通常使用 jQuery 更容易。我在上面的代码中包含了该库,但理想情况下您应该将它添加到&lt;head&gt;。这里我使用$.post函数(documentation

【讨论】:

  • @sukiyo 如果这解决了您的问题,请将其标记为已回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
  • 2012-07-09
  • 2012-07-09
  • 1970-01-01
相关资源
最近更新 更多