我正在尝试jQuery验证。我的代码是:
jQuery.validator.addMethod("isOnlyEmail", function(value, element,param) {
var emailVal;
$.getJSON('get/getAllData.php?operation=email&email='+value, null, function(data) {
alert(data);
if(data==0)
emailVal true;
else
emailVal false;
});
return emailVal;
}, "My message");
如果只返回值为true,我想显示我的消息。但这段代码错了。我的信息会不断显示。
如果我按如下方式更改我的代码:
jQuery.validator.addMethod("isOnlyEmail", function(value, element,param) {
return false;
}, "My message");
显示我的信息。
如果我按如下方式更改我的代码:
jQuery.validator.addMethod("isOnlyEmail", function(value, element,param) {
return true;
}, "My message");
我的信息未显示。
有什么想法吗?
HTML code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery.js"><\/script>')</script>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<!-- Bootstrap jQuery plugins compiled and minified -->
<script type="text/javascript" src="./js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
jQuery.validator.addMethod("isOnlyEmail", function(value, element,param) {
var emailVal;
$.getJSON('get/getAllData.php?operation=email&email='+value, null, function(data) {
alert(data);
if(data==0)
emailVal true;
else
emailVal false;
});
return emailVal;
}, "My Message");
$("#signupform").validate({
rules:{
email:"isOnlyEmail"
},
highlight: function(label) {
$(label).closest('.control-group').removeClass('success');
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error')
.closest('.control-group').addClass('success');
}
});
});
</script>
</head>
<body>
<input id="email" type="email" name="email" placeholder="email@site.com" />
</body>
</html>
PHP代码:
<?php
require_once("../db/dbconnect.php");
$operation = $_GET['operation'];
if($operation == "email"){
$mail=$_GET['email'];
$query = "SELECT * FROM ACCOUNT WHERE email='".$mail."'";
$result = execute_query($query);
echo mysql_num_rows($result);
}
?>
答案 0 :(得分:0)
我的问题解决了。
我按如下方式更改了我的代码:
jQuery.validator.addMethod("isOnlyEmail", function(value, element) {
var emailVal=true;
$.ajax({
url: 'get/getAllData.php?operation=email&email='+value,
type:'GET',
dataType: 'json',
async: false,
success: function (data) {
if(data==0)
emailVal=true;
else
emailVal=false;
},
});
return emailVal;
}, "My Message");
通常,ajax调用是以异步模式运行的。由于异步模式,它不起作用。如果在我的代码中添加了“async:false”,问题就解决了。