问题描述
我是 AJAX
的新手,我想学习如何验证表单.假设我有一个带有两个输入字段的表单.当我单击提交时,我想使用php脚本检查页面.
验证成功后,我想重定向到 action ="submitForm.php"
.根据 validation.php
,当一个或多个字段无效时,我想停留在页面上,并在该字段旁边显示一条错误消息.
I am new to AJAX
, and I want to learn how to validate a form. Suppose, I have a form with two input fields. When I click in submit I want to check the page with a php script.
When the validation is succesfull I want to redirect to the action="submitForm.php"
. When one or more fields are not valid according to the validation.php
I want to stay on the page and gives a error message next to the field.
做到这一点的最佳方法是什么?
What is the best way to do that?
<html>
<head>
</head>
<body>
<form action="submitForm.php" action="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
</html>
submitForm.php:
submitForm.php:
<?php
echo $_POST["username"];
echo "<br />";
echo $_POST["password"];
?>
推荐答案
为了在实际提交表单之前处理字段,您可以捕获其提交事件:
In order to process the fields before actually submitting the form, you can catch its submit event:
<form action="submitForm.php" action="post" onsubmit="return MyValidation()">
然后,在您的JavaScript中:
Then, in your javascript:
function MyValidation() {
var valid = false;
$.ajax({
type: "POST",
url: "validation.php",
async: false,
data: { name: $('#username').val(), password : $('#password').val() }
})
.done(function( data ) {
if(data == 'true') {
valid = true;
}
});
// not valid, return false and show some hidden message
return valid;
}
(您需要在< input>
字段中添加一个ID,以使jquery选择器起作用...)
(you need to add an ID to the <input>
fields in order for the jquery selectors to work...)
这篇关于使用AJAX和JQuery使用PHP进行简单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!