2016-08-19 69 views
2

基本上我有一個窗體,並在該窗體中我有一個用戶名文本框提交按鈕。 現在我想要的是,我們提交表單之前,我想發送文本值到服務器,以便服務器可以檢查用戶名是否沒有被任何其他用戶採取,然後提交表格,根據我的研究,我發現本教程很有用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腳本看,我有一個警報(),它應該彈出打招呼,但它從來不

+0

把event.preventDefault();在您的ajax函數之前的頂部,然後var fromData = $('#your_form_id「)。serialize(); –

+1

您的代碼將在表單提交時觸發。如果您希望在提交之前在服務器上檢查用戶名,應該使用一種不同的方式,例如綁定這個ajax調用一個模糊事件在* username *輸入標籤 –

+0

是的,最好是綁定你的用戶名驗證和模糊不同的事件,就像@MarioAlexandroSantini說的那樣 –

回答

1

早安!

我認爲有幾件事要說你的代碼。首先所有的submit功能:

$('form').submit(function(event) { ... } 

在這裏,你要當用戶點擊該按鈕趕上提交事件。一切都很好,但由於您的按鈕是type=submit,瀏覽器也會對點擊作出反應並自行處理提交過程。您的功能將無法正確調用。爲了防止這種情況,你必須逃脫提交表單的默認行爲:

$('form').submit(function(event) { 
    event.preventDefault(); 

    $.ajax({ ... }); 
} 

這將這樣的伎倆來讓瀏覽器做你想做的,而不是處理自身提交的內容。

所以現在你的瀏覽器可以運行你的ajax調用。

接下來的事情:ajax調用。

你做了很多事情是正確的,但一些重要的事情是錯的。看看下面的結構:

$.ajax({ 
    url:  'your_url_to_send_data_to', 
    type:  'post', //the method to use. GET or POST 
    dataType: 'json', 
    data:  data, //your data: {key1:value1, key2:value2} 
    success: function(data) { //handle a successfull response (200 OK) 
     alert(data); 
     //here you can do with your data whatever you want 
    }, 
    error: function(jqXHR, textStauts, errorThrown){ //handle every error. e.g. 500 
     alert(textStatus + ': '+errorThrown); 
    } 
}}); 

這將處理您的請求的發送和接收。如果服務器返回200 OK,則success函數將被調用。否則將調用error函數。 現在你只需要在服務器端正確處理請求。

第三件事:名稱檢查後真正提交的內容是什麼?

由於您preventDefault()默認的瀏覽器操作,sou必須手動完成。你可能會想到再次觸發提交,但是你會用自己寫的功能再跑一次。 因此你必須自己做。可是等等!您可以在一個電話中結合這兩件事!

想想這個:

  1. 讓用戶填寫表單
  2. 讓他點擊提交按鈕
  3. 瀏覽器的preventDefault行爲,並建立一個FormData,並把所有的值在它
  4. 準備您的阿賈克斯電話
  5. 發送FormData與您的ajax呼叫您的服務器
  6. 網名檢查和服務器端
  7. 回答請求
  8. evalutate答案在你success功能的所有其他的事情

注:在服務器端,您必須打印application/json頭讓瀏覽器,最後你的ajax調用正確處理你的答案。

+0

爲什麼它永遠不會執行我的腳本我帶了event.preventDefault();在$(document).read(function(){仍然沒有運氣,我甚至嘗試過alert('hello');並且沒有結果沒有彈出窗口來打招呼,你知道什麼可能是問題 – rocky

+0

嗯,只是爲了理解你正確的:你在'$(document).ready()'中放入'$('form')。submit()',然後你在''('form')內部跳過默認的**。 (函數(事件){});'和**在**這個函數中你試圖'alert('hello')'? – Otterbein

0

我認爲你應該使用「遠程」的jquery驗證(https://jqueryvalidation.org/remote-method/)這將檢查服務器中字段的驗證。你需要jQuery。

$("#Registration_Form").validate({ 
    rules: { 
    Registeration_Username_box: { 
     required: true, 
     remote: { 
     url: "check-email.php", 
     type: "post" 
     } 
    } 
    } 
}); 
+0

爲什麼它永遠不會執行我的腳本我帶了event.preventDefault() ; $(文檔).read(函數(){仍然沒有運氣,我甚至嘗試過alert('hello');沒有結果沒有彈出窗口來打招呼,你知道可能是什麼問題 – rocky

+0

它是$(document) .ready(function(){not $(document).read(function(){ 也許是這樣嗎? –

1

既然你想要的用戶名可用性的動態檢查,我建議你到KEYUP事件作出反應(注:我還增加了以下我的演示其他可能的變化引起的事件支持)和日程在固定延遲後檢查運行。一旦延遲發生,如果用戶在此期間沒有輸入任何內容,則可以運行AJAX檢查並更新頁面;如果用戶確實在中輸入了某些內容,則可以根本不運行該檢查(還)。這意味着只要用戶至少停止輸入硬編碼延遲,就會在每次打字之後自動執行檢查。

關於提交,我只允許用戶以正常方式提交表單,而不用任何用戶名可用性的最後一次AJAX檢查。您仍然需要執行服務器端可用性檢查,以防用戶禁用JavaScript或以某種方式構建了自己的提交HTTP查詢,因此在提交表單時您可能依賴於該服務器端檢查。動態AJAX檢查實際上只對用戶有用,因此只能在用戶編輯用戶名時提供,並且而不是立即提交表單。大多數情況下,用戶在編輯字段後不會立即提交表單,並且如果頁面上明確指出存在驗證失敗,則可以依賴大多數用戶不提交表單。

var USERNAME_CHECK_DELAY = 800; 
 

 
var userInputValCount = 0; 
 
var userInputVal = ''; 
 

 
window.handlePossibleUserInputChange = function() { 
 
    let $userInput = $('#userInput'); 
 
    let $checkDiv = $('#userCheckLine'); 
 
    // if this event doesn't reflect a value change, ignore it 
 
    if ($userInput.val() === userInputVal) return; 
 
    userInputVal = $userInput.val(); 
 
    // update the value count 
 
    let userInputValCountCapture = ++userInputValCount; // closure var 
 
    // schedule a potential check run 
 
    setTimeout(function() { 
 
    // only check the current name if the user hasn't typed since the provoking event 
 
    if (userInputValCountCapture !== userInputValCount) return; 
 
    checkUsername(); 
 
    },USERNAME_CHECK_DELAY); 
 
    // update the status message 
 
    if ($userInput.val().trim() === '') { 
 
    $checkDiv.text(''); 
 
    } else { 
 
    $checkDiv.attr({'class':'checking'}); 
 
    $checkDiv.text('checking...'); 
 
    } // end if 
 
}; 
 

 
$('#userInput') 
 
    // listen to all events that could cause a change in the input value 
 
    .on('keyup change',handlePossibleUserInputChange) 
 
    // drop is special; the drop event unfortunately fires before the text is changed 
 
    // so we must defer the call until after the text is changed 
 
    // same with mouseup; occurs when clicking the input box X button in IE 
 
    // same with paste via context menu, rather than shortcut (which would trigger keyup) 
 
    .on('drop mouseup paste',function() { setTimeout(handlePossibleUserInputChange); }) 
 
; 
 

 
var lastTaken = true; 
 

 
window.checkUsername = function() { 
 
    let $checkDiv = $('#userCheckLine'); 
 
    let $userInput = $('#userInput'); 
 
    // just reset the check line if the input value is empty 
 
    if ($userInput.val().trim() === '') { 
 
    $checkDiv.text(''); 
 
    return; 
 
    } // end if 
 
    // ... send ajax call, get result ... 
 
    // (for demo purposes, just invert the previous result) 
 
    let taken = lastTaken = !lastTaken; 
 
    if (taken) { 
 
    $checkDiv.attr({'class':'taken'}); 
 
    $checkDiv.text('user name is taken.'); 
 
    } else { 
 
    $checkDiv.attr({'class':'notTaken'}); 
 
    $checkDiv.text('user name is available.'); 
 
    } // end if 
 
};
.taken { color:red; } 
 
.notTaken { color:green; } 
 
.checking { color:grey; font-style:italic; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="form1"> 
 
    <div> 
 
    <input id="userInput" type="text" placeholder="username"/> 
 
    <span id="userCheckLine"></span> 
 
    </div> 
 
    <input type="submit" value="Submit"/> 
 
</form>