簡體   English   中英

onsubmit刷新html表單

[英]onsubmit refresh html form

我正在嘗試使用Javascript提交表單數據。 這是html。

<form onsubmit="post();">
//input fields here
</form>

這是post()函數的Javascript。

var post = function() {
alert('the form was submitted');
return false;
}

我的問題是Javascript可以運行,但是表單仍在處理並刷新頁面。

我把return false; 希望它能阻止表單刷新。

您將必須在onsubmit處理程序中的post()函數之后放置return false部分,如下所示:

<form onsubmit="post();return false;">
//input fields here
</form>

將您的js放在DOM之外。

<form id="myform" action="somepage.php" method="post">
//input fields
</form>

jQuery的:

$('#myform').submit(function(event){
    alert('submitted');
    event.preventDefault();
});

您實際上需要從內聯dom-0處理程序返回false。 所以改變

onsubmit = "post();">

onsubmit = "return post();">

或者,您可以給表單一個ID並執行以下操作:

<form id="form1" onsubmit = "post();">

然后從准備好您的dom的安全位置進行:

document.getElementById("form1").onsubmit = post;

由於您添加了jQuery標簽,因此這是執行此操作的最佳方法:
不顯眼的事件附加

$('form').submit(function(){
        alert('the form was submitted');
        return false;
    });

用你的方式應該;

<form onsubmit="return post();">

由於這篇文章是用jQuery標記的,因此我將提供以下解決方案:

$('form').submit(function(e){
  //prevent the form from actually submitting.
  e.preventDefault();
  //specify the url you want to post to.
  //optionally, you could grab the url using $(this).attr('href');
  var url = "http://mysite.com/sendPostVarsHere";
  //construct an object to send to the server
  //optionally, you could grab the input values of the form using $(this).serializeArray()
  var postvars = {};
  //call jquery post with callback function
  $.post(url, postvars, function(response){
    //do something with the response
    console.log(response);
  }, 'json')
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM