首页 > 解决方案 > 提交后,输入文本消失并重新加载页面(AJAX)

问题描述

为什么我的页面即使我使用了 ajax 也会重新加载,并且在单击提交按钮后它也会消失我的输入文本。我已经使用 show 来解决它,但它不起作用。

<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="text" name="name" id="name">
<span id="namenotif" style="color:red;"> <span>
<br>
<input type="text" name="price" id="price">
 <span id="pricenotif" style="color:red;"> <span>


<br>
<input type="submit" name="submit" id="save"><br>
</form>


<script>  
$(document).ready(function() {
$(document).on("click","#save",function(){
var name = $("#name").val();
var price = $("#price").val();
if(name==""){
  $("#namenotif").html("Enter a name");
  $("#name").show("fast");
     $("#save").show("fast");
}
else if(price==""){
   $("#pricenotif").html("Enter a price");
   $("#price").show("fast");
           $("#save").show("fast");
 }else{
  $.ajax({
    url:"addproduct.php",
    type:"POST",
    data:{name:name,price:price}, 
    success:function(data){
      alert("Successful");
       }
      });
     }
  });
});
</script>

标签: javascriptphpjqueryajaxforms

解决方案


将 return false 添加到函数末尾,用于处理单击事件


推荐阅读