【发布时间】:2019-03-24 01:37:03
【问题描述】:
我正在做一些事情,涉及确保表单提交的方法是 POST 而不是 GET,而该方法可能以某种方式和某处被省略。 JS/jQuery 函数在提交特定类之前检查每个表单。如果该类存在,它将继续检查该方法。如果方法是 GET,它应该忽略它并提交表单。但如果它未定义或为空,则应继续将方法设置为 POST 然后提交。 这是使用的 JQuery。 HTML 如下。
$(document).ready(function() {
$('form').submit(function() {
if (this.find(':submit').is('.ckh-method')) {
if ((this.attr('method') !== "GET" && this.attr('method') == "") || this.attr('method') == undefined) {
this.setAttribute('method', 'POST');
return true;
}
}
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://fontawesome-free/web-fonts-with-css/css/fontawesome-all.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" action="phpFile.php" method="">
<div class="row">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-user-alt"></i>
</span>
<input type="text" class="form-control" placeholder="Username" name="username" id="username" required="required" value=''>
</div>
</div>
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-lock"></i>
</span>
<input type="password" class="form-control" placeholder="Password" name="password" id="password" required="required" value=''>
</div>
</div>
<p class="conditions col-sm-12"><a href="anotherPage.html">Forgot Username or Password?</a>
<div class="text-center col-sm-12 error"></div>
</p>
<div class="col-sm-12" id="btn-hold">
<button type="submit" class="btn btn-success btn-block ckh-method">Log In</button>
</div>
<div class="col-sm-12">
<a type="button" class="btn btn-link btn-block" href="proceed.php">Sign Up</a>
</div>
</div>
</form>
</div>
</body>
</html>
问题:表单方法在提交时没有改变,因为我的代码中某处存在 JS 错误。我怀疑它与“this”关键字有关。也许我用错了。我已经尝试设置断点,以便我可以识别问题,但在我可以进入函数(在我的开发人员工具中)并发现问题之前提交了表单。有人可以帮帮我吗?
【问题讨论】:
-
使用
$(this)而不是this。看这里:stackoverflow.com/questions/1051782/… -
您可以创建一个函数并在提交按钮单击事件上将其单元格。
标签: javascript jquery html forms validation