2013-10-07 158 views
0

我見過很多與此相關的其他問題,但沒有人爲我工作。我正在嘗試提交一個POST表單,然後將用戶重定向到另一個頁面,但我無法讓這兩種情況發生。我可以獲得重定向,或者發佈帖子,但不能同時發佈。這裏是我現在有:提交表單並重定向頁面

<HTML> 
    <HEAD> 
    </HEAD> 
    <BODY> 
     <script type="text/javascript"> 
      function redirect() { 
       window.location.href = "http://www.google.com"; 
      } 
     </script> 
     <form id="myForm" method=POST name=transferform 
      action="some_place.php" onsubmit="redirect();"> 
      <input name=gold type=text value="1" size=5> 
      <input name=recipient type=text value="mypal" size=10> 
      <input id="myButton" type=submit name=submission value="Send"> 
     </form> 
     <script type="text/javascript"> 
      window.onload = function(){ 
       document.getElementById('myButton').click(); 
      }; 
     </script> 

    </BODY> 
</HTML> 

我做錯了什麼?

回答

0

提交表單後,當前頁面上的所有JS執行都會停止。您需要從服務器重定向,或者讓服務器吐出一個包含JavaScript的頁面來執行重定向。

+0

有沒有辦法來控制頁面'form'元素提交後得到的信息? – fvrghl

+0

是的,這是表單的行動。 –

0

您可以透過使用AJAX形式再從服務器接收響應後重定向使用的JavaScript或者,如果你想要做的全網頁提交,那麼你可以使用Location頭使用PHP重定向頁面:

header('Location: http://somewebsite.com/somepage.php'); 
0

考慮使用延遲覆蓋覆蓋表單的默認提交行爲。

$('#myForm').submit(function (e) { 
    // prevent form submission 
    e.preventDefault(); 
    var thisForm = $(e.currentTarget); 
    $.ajax({ 
     // simulate form submission 
     type: thisForm.attr('method') || 'POST', 
     url: thisForm.attr('action') || window.location.href, 
     data: $.serialize(thisForm.data()) 
    }) 
    .always(function() { 
     // when it is done submitting data to the server, redirect 
     window.location.replace("http://www.google.com"); 
    }); 
}); 
0

您可以通過Ajax請求發佈表單,完成請求後將其重定向到新頁面。

是這樣的:

<HTML> 
<HEAD> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
</HEAD> 
<BODY> 
<form id="myForm" method=POST name=transferform action="some_place.php" onsubmit="return false;"> 
    <input name=gold type=text value="1" size=5> 
    <input name=recipient type=text value="mypal" size=10> 
    <input id="myButton" type=submit name=submission value="Send"> 
</form> 

<script type="text/javascript"> 
    $(function() { 
    $(document).on("submit", "#myForm", function(event){ 
     var name = $('input[name="gold"]:first'), 
     recipient = $('input[name="recipient"]:first'); 
     $.post("some_place.php", { name: name, recipient: recipient }) 
     .done(function(data) { 
     window.location.href = "http://www.google.com"; 
     }); 
    }); 
    }); 
</script> 
</BODY> 
</HTML> 
相關問題