json向控制器发送空值

时间:2013-07-30 07:32:09

标签: jquery json spring spring-mvc jquery-validate

我正在使用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将null值发送给方法

这是我的控制器方法:

@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'变量显示如下=&gt; []

请帮我解决这个问题。提前致谢。

1 个答案:

答案 0 :(得分: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();
        }
    }