首页 > 解决方案 > 单击提交按钮后页面重新加载

问题描述

$(document).ready(function() {
  $("submit").click(function(event) {
    event.preventDefault();
  });
});

function norefresh() {
  return false;
}
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
  <div class="form-group">
    <div class="row">
      <div class="col-xs-6 col-md-6 form-group">
        <label for="lname1">NAME OF THE LANDLORD</label>
        <input type="text" class="form-control" id="lname" name="lname"></div>
      <div class="col-xs-6 col-md-6 form-group">
        <label for="lpan1">PAN OF LANDLORD</label>
        <input type="text" class="form-control" id="lpan" name="lpan">
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="row">
      <div class="col-xs-6 col-md-6 form-group">
        <label for="ladd1">ADDRESS OF LANDLORD</label>
        <input type="text" class="form-control" id="ladd" name="ladd">
      </div>
      <div class="col-xs-6 col-md-6 form-group">
        <label for="lacc1">ACCOMODATION ADDRESS</label>
        <input type="text" class="form-control" id="lacc" name="lacc">
      </div>
    </div>
  </div>

  <input type="submit" class="btn btn-primary pull-right" name="submit" value="Add New" onClick="getintotab();resetform();return false;" />
  <br> <br>
</form>
</div>
<?php
	if(isset($_POST['submit'])){
		$sql1 = $db->query("INSERT INTO Landlord(name, landlord_pan, landlord_address, acc_address) VALUES ('".$_POST["lname"]."','".$_POST["lpan"]."','".$_POST["ladd"]."','".$_POST["lacc"]."')");
	
		if($sql1 == TRUE){
			echo "";
		} 
		else{
			echo "Error: " . $sql1 . "<br>" . mysqli_error($db);
		}
	}
?>

单击提交按钮时的 php 脚本将表单数据发送到 mysql 数据库,该getintotab()函数将表单值存储在表中的同一页面上,resetform()重置表单,但单击提交按钮时,页面会重新加载。
我已经尝试过以下方法:

  1. norefresh()
  2. preventdefault()
  3. 将输入类型设置为按钮而不是提交

仍然没有运气

标签: javascriptphpjqueryhtmlajax

解决方案


您需要使用 event.preventDefault() 但您的选择器“提交”不会匹配任何内容。

将标识符添加到您的提交按钮:

<input type="submit" id="submit" ... >

然后将其用作您的选择器:

  $("#submit").click(function(event) {
    event.preventDefault();
    # You should add the other function calls here 
    # instead of having function calls in two separate places.
  });

或者在您的表单中添加一个标识符:

<form id="form" ... >

然后为提交操作添加一个监听器(我推荐的方式):

  $("#form").submit(function(event) {
    event.preventDefault();
    # You should add the other function calls here 
    # instead of having function calls in two separate places.
  });

推荐阅读