如何在没有使用ajax提交表单的情况下检查服务器上的文本框值可用性

时间:2016-08-19 18:35:14

标签: javascript jquery html ajax forms

基本上我有一个表单,并且在该表单中我有一个带有提交按钮的用户名文本框。现在我想要的是,在我们提交表单之前,我想将文本值发送到服务器,以便服务器可以检查用户名是否未被任何其他用户使用,然后根据我的研究提交表单,我发现本教程很有用https://scotch.io/tutorials/submitting-ajax-forms-with-jquery,尽管本教程使用php进行服务器编码,我正在使用java servlet,但我的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) {

event.preventDefault();
alert('hello');
// 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
 });

 });

  </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~`!@#\(\.)]+$/)){
    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脚本中看到的那样,我有一个警告()它应该弹出你好,但它永远不会

0 个答案:

没有答案