基本上我有一個窗體,並在該窗體中我有一個用戶名文本框提交按鈕。 現在我想要的是,我們提交表單之前,我想發送文本值到服務器,以便服務器可以檢查用戶名是否沒有被任何其他用戶採取,然後提交表格,根據我的研究,我發現本教程很有用https://scotch.io/tutorials/submitting-ajax-forms-with-jquery,儘管本教程使用php進行服務器編碼,我使用的是java servlet,但我的ajax腳本永遠無法執行。如何發送文本值到服務器沒有提交表單使用AJAX
這裏是我的代碼:
<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script>
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'username' : $('input[name=UserName]').val(),
};
alert('hello');
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../postr', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
name="UserName" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" maxlength="30" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
<script>function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
if (field.value == '') {
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
document.getElementById(errordiv).style.visibility = "visible";
} else if(!field.value.match(/^[a-zA-Z0-9~`[email protected]#\(\.)]+$/)){
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "visible";
document.getElementById(errordiv).style.visibility = "hidden";
} else {
field.style.borderColor = "rgb(150,150,150)";
document.getElementById(errordiv).style.visibility = "hidden";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
}
}</script>
,你可以在我的AJAX腳本看,我有一個警報(),它應該彈出打招呼,但它從來不
把event.preventDefault();在您的ajax函數之前的頂部,然後var fromData = $('#your_form_id「)。serialize(); –
您的代碼將在表單提交時觸發。如果您希望在提交之前在服務器上檢查用戶名,應該使用一種不同的方式,例如綁定這個ajax調用一個模糊事件在* username *輸入標籤 –
是的,最好是綁定你的用戶名驗證和模糊不同的事件,就像@MarioAlexandroSantini說的那樣 –