Javascript 提交后,输入文本消失并重新加载页面(AJAX)
为什么我的页面即使使用ajax也会重新加载,而且在单击submit按钮后,我的输入文本也会消失。我已经用show解决了这个问题,但它不起作用Javascript 提交后,输入文本消失并重新加载页面(AJAX),javascript,php,jquery,ajax,forms,Javascript,Php,Jquery,Ajax,Forms,为什么我的页面即使使用ajax也会重新加载,而且在单击submit按钮后,我的输入文本也会消失。我已经用show解决了这个问题,但它不起作用 <form method="POST" action="<?php $_SERVER['PHP_SELF'];?>"> <input type="text" name="name" id="name"> <span id="namenotif" style="color:red;"> <span>
<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>
由于type=“submit”的原因,其
使用
<input type="button" name="submit" id="save"><br>
或
<a href="javascript:void(0) id="save">
将return false添加到函数末尾,该函数处理单击事件两种解决方案:
将按钮type='submit'
更改为type='button'
或(最好是)
将事件侦听器更改为侦听表单的onSumbit
事件,然后调用event.preventDefault
或在jQuery中,我认为您只需在回调中执行返回false
我认为表单正在被提交,因为提交表单是提交按钮的默认行为,无论您是否使用ajax。因此,您可以通过在jquery中简单地添加代码来防止默认行为。按如下方式修改代码:
$(document).on("click","#save",function(e){
e.preventDefault();
...............
其余代码可以保持不变。因此,只有防止默认操作,它应该可以工作。使用type按钮而不是submit for button可能的重复我不明白您为什么不分离保存和验证操作将帮助您解决问题。我是否应该在表单标记和操作中包含post,即使我使用了ajax?使用ajax提交数据时,不需要在表单标记中包含操作或方法。我有观察到,当我提交表单时,一次只需要一个字段。我想这是因为我使用的条件。