2012-02-12 61 views
0

我嘗試使用ajax驗證字段,並驗證該值是否已經基於該值。jquery驗證引擎:使用java(不使用php)驗證ajax字段

我發現的所有例子都與PHP;如何用java?

JSP代碼:

<form id="FLoginNew" action="Loginnew" method="post"> 
..... 
<script> 
$(document).ready(function(e) { 
    $("#FLoginNew").validationEngine('attach', {promptPosition : "centerRight", scroll: false, validationEventTrigger: "blur", autoHidePrompt:true, autoHideDelay:3000 }); 
}); 
</script> 

jquery.ValidationEngine-fr.js改變:

"ajaxLoginCall": { 
       "url": "myapp.selvlets.DoublonLoginServlet", 
       "extraDataDynamic": ['#login'], 
       "alertText": "* Ce login est déjà pris", 
       "alertTextOk": "* Ce login est disponible", 
       "alertTextLoad": "* Chargement, veuillez attendre" 
      }, 

作爲URL,我想:"url": "/DoublonLogin",其爲servlet映射的宣言web.xml中。

回答

0

我回答自己:我找到了解決辦法:

首先,輸入級(我沒有顯示):class="validate[required,ajax[Ajaxdoublonlogin]]"

然後,Ajax調用名爲「Ajaxdoublonlogin」的網址:"Doublonlogin",因爲它在web.xml文件中聲明。這是一個servlet。

該servlet:

  • 必須導入JSON librairy。我選擇了「JSONSimple」:簡單並且足夠我想要做的事情。
  • 創建JSON數組,然後將輸入字段的名稱設爲真或假 進行驗證。
  • 在響應對象中創建一個寫入器並寫入JSON數組。

沒什麼難!^_^

例:「登陸」是輸入域的id

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    String login = new String(request.getParameter("login")); // we catch the value 

    JSONArray jsres = new JSONArray(); // new JSON array 

    jsres.add("login"); // 1st field : the field name = "login" 

    if(<login in the database ?>) jsres.add(new Boolean(false)); // In database ? => false in the JSON array 
    else jsres.add(new Boolean(true)); // Not in database > true in the JSON array !! 

    response.setContentType("application/json"); // The answer is in JSON content type 
    response.setCharacterEncoding("UTF-8"); // Put the right encoding 
    PrintWriter writer = response.getWriter(); // new answer writer 

    try { 
     writer.println(jsres); // WRITE !! ^_^ 
     log.info("Retour JSON : " + jsres); 
     } catch(Exception e){ 
     log.error("Erreur lors du transfert JSON : " + e.getMessage()); 
    } finally { 
     writer.close(); // Don't forget to close the writer 
    } 
} 

它工作正常... 如果您有任何建議,我會採取與快感!

現在,我會盡量防止表單提交,因爲如果最後一個條件是這種情況,提交會附加;我不知道爲什麼...