嗨!您好:
我對Jquery和web開發很陌生,所以請耐心等待。 我要實現我的網站上使用jQuery實時輸入驗證。也許我在這篇文章中有一些語法錯誤,但我確信我沒有任何在我的真實代碼中。
這是我有什麼,只要用戶輸入的東西是不是空白的錯誤()將被調用,使POST請求到服務器(PHP + MySQL的),以檢查是否輸入值已經存在。當按下提交按鈕時,錯誤()也會再次使用。
之前,我按下提交按鈕這工作完全正常。如果我輸入了已存在的內容,表單將不會被提交。但是如果我輸入新的東西,即使數據仍然插入到數據庫中,我仍然會得到(「存在」)文本。 (「成功」)後,我將永遠得到(「存在」)。看起來像我提交時,error()中的.post請求是在表單的.post請求之後進行的。有沒有人如何解決這個錯誤?或另一種方式來構建這種類型的輸入驗證? 謝謝
$('.unique').change(function(){
error($(this));
});
function error(obj)
{
var ok = true;
if(obj.val().length == 0)
{
alert('This field can not be blank');
ok = false;
}
else
{
var data = "action=check&input=" + obj.attr('name') + "&value=" + obj.val();
$.post('database.php',
data,
function(reply){
if(reply == true)
{
alert("This " + obj.attr('name') + " already exists");
ok = false;
}
});
}
return ok;
}
//When the user submits the form
$('#info').submit(function(){
var ok = true;
var data = 'action=insert&' + $(this).serialize();
//Passes each input to the error()
$('.unique').each(function{
var temp = error($(this));
ok = ok && temp;
});
if(!ok) return false;
$.post('database.php',
data,
function(reply){
alert(reply);
});
});
<form id="info" name="info" action="" method="post">
<input type ="text" class = "unique" id = "username" name = "username" class = "unique">
<input type ="text" class = "unique" id = "email" name = "email" class = "unique">
</form>
//On the server
if(isset($_POST['action']))
{
if($_POST['action'] == 'check')
{
$query = sprintf("select * from Users where %s = '%s'",
$_POST['input'],
$_POST['value']);
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{ echo true;}
else
{ echo false;}
}
else
{
$query = sprintf("insert into Users(username, email) values('%s','%s')",
$_POST['username'],
$_POST['email']);
if(!($result = mysql_query($query)))
die(mysql_error());
echo 'Success';
}
}
您可以編輯您的文章,幷包括ERR()函數,從我收集的計時問題與在製作每個帖子的結果驗證,要等待每個崗位試圖插入操作 –
阿爾莫格您好我確實包括在後的錯誤()之前完成,感謝 – Nooooooob
我彪此行=>變種臨時= ERR($(本)); 它實際上變種臨時=錯誤($(本)); ?? –