gpt4 book ai didi

jquery - 防止基于jquery中的全局错误提交

转载 作者:行者123 更新时间:2023-12-03 08:00:51 24 4
gpt4 key购买 nike

在html中:

<form action="next.html">
<!-- tags here -->
<button id="prev">Prev</button>
<button id="next">Next</button>
</form>

在Javascript中:
$("form").submit (function(e) {
e.preventDefault();
if (e.originalEvent.explicitOriginalTarget.id == "next") {
doPostData();
// window.location = "next.html";
}
else if (e.originalEvent.explicitOriginalTarget.id == "prev") {
window.location = "prev.html";
}
}

我已根据 here示例向 $(document).ajaxError附加了一个用于解析代码的全局错误处理程序
doPostData()基本上将POST请求发送到服务器。成功完成后,一切都很好,但是当我收到错误消息时,我不知道如何阻止表单提交。错误闪烁,浏览器重定向到“下一页”页面。

我该如何优雅地解决这个问题?

最佳答案

只是为了后代,我终于弄清楚出了什么问题:

错误处理程序已正确触发,但是由于仍然存在window.location = "next.html",因此仍然发生了重定向到下一页的操作。类似于从上面代码中的window.location行中删除注释。

因此,请进行基本设置,并考虑到上面的代码仅适用于FireFox(不适用于Chrome或Safari):

$(document).ajaxError(genericAjaxErrorHandler);

$("#prev").click(function() {
window.location = "prev.html";
});

$("#next").click(function() {
doPostData();
});

function doPostData() {
// actions here

if (allIsOk) {
window.location = 'next.html';
}
}

我加了一个
$('form').submit( function(e) {
e.preventDefault();
});

可以肯定,但是可能没有必要。

关于jquery - 防止基于jquery中的全局错误提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16882630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com