2012-02-12 62 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 
    } 
} 

它工作正常... 如果您有任何建议,我会采取与快感!

现在,我会尽量防止表单提交,因为如果最后一个条件是这种情况,提交会附加;我不知道为什么...