2

我正在使用 jquery.validate.js 验证表单,我需要识别重复的条目,为此我使用自定义方法,即:

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 向该方法发送空值

这是我的控制器方法:

@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 发送 null)。2.在上述方法中,我不认为'if语句有写入条件',因为当数据库中不存在'name'时,'matched'变量显示如下=> []

请在这个问题上帮助我。提前致谢。

4

1 回答 1

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);
            }
        });

并将您的控制器处理程序修改为
注意注释的前两行和@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();
        }
    }
于 2013-07-30T08:04:09.997 回答