繁体   English   中英

提交表格并留在同一页面上?

[英]Submit form and stay on same page?

我有一个看起来像这样的表格

<form action="receiver.pl" method="post">
  <input name="signed" type="checkbox">
  <input value="Save" type="submit">
</form>

当我点击提交时,我想留在同一页面,但仍然执行了receiver.pl

应该怎么做?

最简单的答案:jQuery。 做这样的事情:

$(document).ready(function(){
   var $form = $('form');
   $form.submit(function(){
      $.post($(this).attr('action'), $(this).serialize(), function(response){
            // do something here on success
      },'json');
      return false;
   });
});

如果要动态添加内容并仍需要它可以使用,并且还需要多个表单,则可以执行以下操作:

   $('form').live('submit', function(){
      $.post($(this).attr('action'), $(this).serialize(), function(response){
            // do something here on success
      },'json');
      return false;
   });

99%的时间我会使用XMLHttpRequestfetch来做这样的事情。 但是,有一个替代解决方案,不需要javascript ...

您可以在页面上包含隐藏的iframe,并将表单的target属性设置为指向该iframe。

<style>
  .hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>

<iframe name="hiddenFrame" class="hide"></iframe>

<form action="receiver.pl" method="post" target="hiddenFrame">
  <input name="signed" type="checkbox">
  <input value="Save" type="submit">
</form>

我很少会选择这条路线。 一般用javascript处理它更好,因为使用javascript你可以......

  • 优雅地处理错误(例如重试)
  • 提供UI指标(例如加载,处理,成功,失败)
  • 在发送请求之前运行逻辑,或在收到响应后运行逻辑。

HTTP / CGI方法是让程序返回HTTP状态代码204(无内容)。

当您点击提交按钮时,页面将被发送到服务器。 如果要将其发送为异步,可以使用ajax进行。

使用XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array()); 
// xhr.send(document);

只需使用: action="" 没有像javascript这样的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM