问题
<script type="text/javascript">
$(document).ready(function() {
jQuery(function($){
$("#form").submit(function(e){
if ($(this).valid()){
$.ajax( {
type: "POST",
url: "http://localhost/My/modules/validate.php",
});
}
return false;
})});
$("#form").validate({
rules: {
user: {
remote: {
url: "http://localhost/My/modules/validate.php",
async: false,
}
}
}
});
});
$.validator.setDefaults({
debug: true,
success: "valid",
});
</script>
I want to create remote validation rules. This example correctly reads ajax requests. Though returning true/false both evaluate to validation error.
However, deleting ajax part (jQuery()) results in lack of ajax initialization, the request isn't even handled.
async: false seems to be passive, deleting this results in the same thing.
Anyone could have any slightest idea what could be wrong here?
EDIT:
$(document).ready(function() {
$("#form").validate({
rules: {
user: {
remote: "http://localhost/My/modules/validate.php",
}
},
submitHandler: function (form) {
// do your ajax form submission here
return false; // prevent redirect since you did ajax
}
});
});
</script>
回答1:
You do not need an external submit
handler when using the Validate plugin because it already has all the event handlers built in.
The built-in submitHandler
is only fired whenever the form is valid and it's where you'd put any ajax
for form submission.
You are doing ajax
in two places... with the remote
rule and with your submit
handler.
- Use the
remote
rule if your ajax is used for validating a field. - Use
submitHandler
if your ajax is used for form submission.
This is using only the remote rule, as per documentation:
$(document).ready(function () {
$("#form").validate({
rules: {
user: {
// ajax in remote rule to check this field
remote: "http://localhost/My/modules/validate.php"
}
}
}
});
});
// get rid of all this
//$.validator.setDefaults({
//debug: true, // not needed in production
//success: "valid", // this is already the default.
//});
The following is only my suggestion if you're using ajax for form submission. Ignore it otherwise.
This is using the submitHandler callback, as per documentation:
$(document).ready(function () {
$("#form").validate({
// your rules & options,
submitHandler: function (form) {
// do your ajax form submission here
return false; // prevent redirect since you did ajax
}
});
});
来源:https://stackoverflow.com/questions/15116585/jquery-remote-validation-rule