簡體   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