0
我需要使用Ajax驗證我的表單字段。
我現在所擁有的是一個javascript驗證。 我想知道是否有可能重新使用我的JavaScript代碼,並實現Ajax使用Ajax調用服務器驗證表單字段 - 學習Ajax
HTML表單
<form method="post" action="ajax/validation.php" class="ibm-row-form" id="registerform">
<h2 class="ibm-inner-subhead">Basic registration information</h2>
<p>
First name: <span class="ibm-required">*</span><br/>
<input id="firstName" name ="firstName" size="36" type="text" onblur=" validateFirstName();" />
<span id="errorFName" class="error">First name is required</span>
</p>
<p>
Last name:<span class="ibm-required">*</span><br/>
<input name="lastName" id="lastName" size="36" type="text" onblur="validateLastName();" />
<span id="errorLName" class="error">Last name is required</span>
</p>
<input id="ibm-submit" name="ibm-submit" class="ibm-btn-arrow-pri" value="Register" type="submit" />
<input value="Cancel" type="button" name="ibm-cancel" class="ibm-btn-cancel-sec" onclick="window.location(window.location.href = '#')" />
</form>
JavaScript驗證(不阿賈克斯)
function validateFirstName(){
var fName = document.getElementById("firstName").value;
if(fName==""){
errorFName.style.visibility = "visible";
return false;
}
errorFName.style.visibility = "hidden";
}
function validateLastName(){
var LName = document.getElementById("lastName").value;
if(LName==""){
errorLName.style.visibility = "visible";
return false;
}
errorLName.style.visibility = "hidden";
}
Ajax驗證(這就是我想要做的)
$('form.ajax').on('submit',function(){
var that = $(this);
url = that.attr('action');
method = that.attr('method');
data = {};
that.find('[name]').each(function(index,value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data : data,
success: function(response){
console.log(response);
}
});
return false;
});
因此,我應該如何解決方案來實現我的Javascript代碼中的Ajax。如何合併這些代碼以驗證表單字段?
謝謝!
感謝。但是,當我這樣做時,它不會執行ajax驗證。 –
@IsadoraAlmeida Ajax驗證是什麼意思?你想在服務器端驗證,但用Ajax提交? – Qianyue
我需要驗證表單字段與服務器的ajax調用。 –