e.preventDefault在表单提交时被忽略
e.preventDefault being ignored on form submitting
本文关键字:表单提交 preventDefault 更新时间:2023-09-26
当我点击下面所示的任何按钮时,php页面getkey.php正被打开,而它不应该被打开,因为我使用的是e.preventDefault();id="getgame"与我的javascript代码中的相同。这让我很恼火,因为除了e.preventDefault();正在按预期运行。value="通过$_GET["appid"]传递,它以0作为1进行响应。
<form action="getkey.php" method="get" class="getgame">
<button name="appid" type="submit" value="112">Request</button>
</form>
<form action="getkey.php" method="get" class="getgame">
<button name="appid" type="submit" value="113">Request</button>
</form>
<form action="getkey.php" method="get" class="getgame">
<button name="appid" type="submit" value="114">Request</button>
</form>
<script>
$(function(){
$('form.getgame').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$('#result').html('');
},
success: function(data){
$('#result').html(data);
if(data === "0") {
alert("foo");
}
if(data === "1") {
alert("bar");
}
}
});
});
});
</script>
首先,不能对多个元素使用相同的id。
将所有表单的id
属性更改为class
,如此
<form action="getkey.php" method="get" class="getgame">
然后在JS中,使用return false;
而不是e.preventDefault()
像这个
$('form.getgame').on('submit', function(e){
//your ajax stuffs here
return false;
});
注:jQuery serialize()
不包括button
或input[type=submit]
,因此您必须手动添加
所以你的JS看起来像
$(function(){
$('form.getgame').on('submit', function(e){
// now do whatever you want here
var appid = $(this).find("button[type=submit]").attr("value");
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: { "appid" : appid }, // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$('#result').html('');
},
success: function(data){
$('#result').html(data);
if(data === "0") {
alert("foo");
}
if(data === "1") {
alert("bar");
}
}
});
// prevent native form submission here
return false;
});
});
相关文章:
- HTML表单提交时未执行外部函数
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 将图像上传ajax与表单提交ajax相结合
- Javascript无法处理表单提交
- 如何在我的情况下禁用表单提交
- 加载后的页面与ajax表单提交不起作用
- angularjs-控制器在表单提交时未调用
- 禁用带有字符白名单的表单提交
- 如何使用Google Analytics跟踪表单提交
- 使用javascript将表单提交到iframe目标中
- e.preventDefault在表单提交时被忽略
- AngularJS JQuery Ajax表单提交等效
- JavaScript表单提交帮助
- PHP表单提交和重定向
- 当所有输入文本字段都为空时,禁止表单提交,但当jquery中的任何字段不为空时允许提交
- setTimeOut AFTER jQuery表单提交
- 从函数中选择要触发表单提交的正确元素
- JavaScript表单提交没有't fire asp服务器端点击功能的提交按钮
- 表单提交问题,如何在我的URL末尾获得ID的值
- Javascript使用Confirm取消表单提交