2013-07-30 85 views
2

我使用jquery.validate.js验证表单,我需要找出重复的条目,为此我使用自定义的方法,即:JSON发送空值到控制器

jQuery.validator.addMethod("uniqueName", function(name, element) { 
     var response; 
     $.ajax({ 
      type: "POST", 
      dataType : "json", 
      url:"${pageContext.request.contextPath}/company/getDuplicate", 
      data:"name="+name, 
      async:false, 
      success:function(data){ 
       response = data; 
      }, 
      error: function (data) { 
       alert(request.responseText); 
      } 
     }); 
    }, "Name is Already Taken"); 

在规则部分:

rules : { 
      name : { 
       required : true, 
       uniqueName : true 
       } 
     }, 
     errorElement : "span", 
     messages : { 
      name : { 
       required : "Name Is Required" 
      } 
     } 

这是我的JSP代码:

<label>Name:</lable> 
<form:input path="name"></form:input> 

它打到指定的URL,但Json的发送空VALU e将方法

这是我的控制器方法:

@RequestMapping(value = "/company/getDuplicate", method = RequestMethod.POST, headers = "Accept=*/*") 
    public @ResponseBody void getTitleList(HttpServletRequest request, HttpServletResponse response) { 

     JSONObject json = new JSONObject(); 
     String data = ((String)json.get("name")); 
     List<Company> matched = companyService.getDuplicate(data); 
     if(matched != null && !"".equals(matched)){ 
      json.put("name", "present"); 
      System.out.flush(); 
     } 
     else{ 
      json.put("name", "notPresent"); 
      System.out.flush(); 
     } 
    } 

我想要的是:1。 如何发送文本框中的值设置为控制器(JSON发送我的情况下空)。 2.在上面的方法中,我不认为'如果语句有写条件',因为当数据库中不存在'名称'时,'匹配'变量显示像这样=> []

请帮助我的问题。提前致谢。

+0

你可以尝试字符串化()你的数据?而且你的代码出错了:“”。我不认为这是问题所在,但你应该纠正 – Okazari

回答

0

如下修改代码:

$.ajax({ 
      type: "POST", 
      dataType : "json", 
      url:"${pageContext.request.contextPath}/company/getDuplicate", 
      data:{"name":name}, 
      async:false, 
      success:function(data){ 
       response = data; 
      }, 
      error: function (data) { 
       alert(request.responseText); 
      } 
     }); 

和修改你的控制器处理程序
通知的注释前两行,并在方法签名addtional @RequestParam(value="name") String name

@RequestMapping(value = "/company/getDuplicate", method = RequestMethod.POST, headers = "Accept=*/*") 
    public @ResponseBody void getTitleList(@RequestParam(value="name") String name,HttpServletRequest request, HttpServletResponse response) { 

     //JSONObject json = new JSONObject(); 
     //String data = ((String)json.get("name")); 
     List<Company> matched = companyService.getDuplicate(name); 
     if(matched != null && !"".equals(matched)){ 
      json.put("name", "present"); 
      System.out.flush(); 
     } 
     else{ 
      json.put("name", "notPresent"); 
      System.out.flush(); 
     } 
    } 
+0

谢谢我从json获取数据,但是它显示了每个数据的现状,即使没有重复... –