ajax提交后如何防止页面刷新
Posted
技术标签:
【中文标题】ajax提交后如何防止页面刷新【英文标题】:How to prevent page from refreshing after ajax submit 【发布时间】:2021-12-26 21:42:32 【问题描述】:我刚开始在工作中使用 Ajax 功能,对它不是很熟悉。我有这个问题,当我提交数据时,它在不刷新页面的情况下提交,但是在第二次尝试提交时,页面在提交之前刷新。我使用了 e.preventDefault() 来防止页面刷新,但它对我不起作用。看来我做的不对。
这是我的 Ajax 代码
<!--AJAX PROCESS TO SUBMIT CHECKED COURSES-->
$(document).ready(function()
loadNewCourse();
loadDelTable();
$('#submit').click(function()
$('#form').submit(function(e)
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i)
var checked = $(this).is(':checked');
if(checked)
in_arr.push($(this).val());
);
$.ajax(
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data:
post_inId : in_arr,
name : name,
email : email,
regno : regno,
level : level,
dept : dept,
semester : semester
,
success: function(data)
loadNewCourse();
loadDelTable();
// setTimeout(function()
// $('#regModal').modal('hide');
// , 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal(
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
)
,
error: function(data)
swal("Oops...", "Registration failed.", "error");
);
);
);
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#deleteCheck').click(function()
$('#delform').submit(function(e)
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i)
var checked = $(this).is(':checked');
if(checked)
id_arr.push($(this).val());
);
swal(
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
,
function(isConfirm)
if(isConfirm)
$.ajax(
type: "POST",
url: "submit.php",
data:
post_id : id_arr,
regno : regno,
level : level
,
cache: false,
async: false,
success: function(data)
// console.log(data);
loadDelTable();
loadNewCourse();
swal(
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
)
,
error: function(data)
swal("Oops...", "Delete failed.", "error");
);
else
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
);
return false;
///////////////////////////////////////////////////////////////////////////////////////////
);
);
function loadNewCourse()
$.ajax(
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data:
loadit : 1
,
success: function(disp)
$("#reveal").html(disp).show();
);
function loadDelTable()
$.ajax(
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data:
loadDel : 1
,
success: function(deldisp)
$("#showRegtbl").html(deldisp).show();
);
);
这是显示提交数据的页面
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><a href="#regModal" data-toggle="modal" data-target="#regModal"><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></a></p>
</div>
</div><br>
<!--Display Courses that are available-->
<span id="reveal"></span>
<!--Table to display courses registered-->
<span id="showRegtbl"></span>
</div>
</div>
我已经被困在这里超过 3 天了。有人可以帮我吗?
【问题讨论】:
您不应该在$("#submit").click()
中包含$("#form").submit()
。只需使用$("#form").submit()
。
完全是@Barmar!!它会绑定提交事件的点击次数。
@Barmar,那么我如何告诉脚本在没有按钮单击事件的情况下单击了哪个按钮? $("#submit").click() 是在表单提交之前单击的按钮。你能告诉我怎么做吗?
@NdongesitEdet $('#form').submit(function(e)
足以确定表单是否已提交,并记住该表单应该是有效的可提交表单。
我只使用了$("#submit").click()
,但它仍然做同样的事情。 @Barmar
【参考方案1】:
我想你误解了表单的提交甚至处理。
表单的默认动作即提交可以用input type="submit"
或<button>
完成
默认
<h2> Form default action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit">
</form>
为了防止表单的默认操作,您可以做 2 件事。
避免使用type="submit"
或按钮
做这样的事情
function customForm()
alert("Hey this is custom handler, dont worry page will not refresh...!");
<h2> Form with custom action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="button" value="submit" onclick="customForm()">
</form>
使用 event.preventDefault()
$('#myform').submit(function(e)
e.preventDefault();
alert("custom handler with preventDefault(), no reload no worries...!");
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2> Form with custom handler using preventDefault() </h2>
<form id="myform" action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit" onsubmit="customForm(this)">
</form>
如有任何疑问,请发表评论。
【讨论】:
您所展示的内容是真实的并且很好理解。我在我的工作中应用了同样的方法,但由于某些我无法弄清楚的原因,在第一次 Ajax 提交后页面仍然在提交时刷新而没有刷新。 @Mohammed Khurram 最后做一些调试,我看不出ajax调用有什么问题,不要使用$("#submit").click()
更好地使用$('#form').submit(function(e)
,就像Barmar的回答一样。 @NdongesitEdet【参考方案2】:
调用$("#form").submit(function() ... )
会在下一次 提交表单时创建一个处理程序。在$("#submit").click()
的处理程序中这样做是不正确的。单击提交按钮将为下一次提交建立一个处理程序,但随后默认操作将立即提交表单,从而刷新页面。将e.preventDefault()
放在点击处理程序中会阻止重新加载,但是您必须单击两次才能提交表单(这实际上不起作用,因为提交按钮的默认操作是触发提交事件,并且你正在阻止)。
只需为每个表单创建提交处理程序,而不是在点击处理程序中进行。
$(document).ready(function()
loadNewCourse();
loadDelTable();
$('#form').submit(function(e)
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i)
var checked = $(this).is(':checked');
if (checked)
in_arr.push($(this).val());
);
$.ajax(
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data:
post_inId: in_arr,
name: name,
email: email,
regno: regno,
level: level,
dept: dept,
semester: semester
,
success: function(data)
loadNewCourse();
loadDelTable();
// setTimeout(function()
// $('#regModal').modal('hide');
// , 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal(
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
)
,
error: function(data)
swal("Oops...", "Registration failed.", "error");
);
);
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#delform').submit(function(e)
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i)
var checked = $(this).is(':checked');
if (checked)
id_arr.push($(this).val());
);
swal(
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
,
function(isConfirm)
if (isConfirm)
$.ajax(
type: "POST",
url: "submit.php",
data:
post_id: id_arr,
regno: regno,
level: level
,
cache: false,
async: false,
success: function(data)
// console.log(data);
loadDelTable();
loadNewCourse();
swal(
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
)
,
error: function(data)
swal("Oops...", "Delete failed.", "error");
);
else
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
);
return false;
///////////////////////////////////////////////////////////////////////////////////////////
);
function loadNewCourse()
$.ajax(
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data:
loadit: 1
,
success: function(disp)
$("#reveal").html(disp).show();
);
function loadDelTable()
$.ajax(
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data:
loadDel: 1
,
success: function(deldisp)
$("#showRegtbl").html(deldisp).show();
);
);
如果您在同一个表单中有多个提交按钮,您应该为每个按钮分配click
处理程序,但不为表单创建submit
处理程序。
【讨论】:
【参考方案3】:感谢大家的帮助。我最后做了一些调试,并且能够通过从添加和删除脚本中删除表单标签来解决问题,然后将它们包含在显示提交数据的页面中。 像这样……
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><a href="#regModal" data-toggle="modal" data-target="#regModal"><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></a></p>
</div>
</div><br>
<!--Display Courses that are available-->
<form id='form' action='POST' href='#'>
<span id="reveal"></span>
</form>
<!--Table to display courses registered-->
<form id='delform' action='POST' href='#'>
<span id="showRegtbl"></span>
</form>
</div>
</div>
有没有更合适的方法来做到这一点,或者这样就可以了?感谢您迄今为止的帮助。
【讨论】:
以上是关于ajax提交后如何防止页面刷新的主要内容,如果未能解决你的问题,请参考以下文章