JQuery 验证 - 如何在 "remote" 方法中正确检索表单字段值?

JQuery Validation - How to correctly retrieve form field value in "remote" method?

使用 jQuery 验证插件,我一直在尝试检索表单的输入字段值,将它与一些 url 前缀连接起来以生成 REST url,然后生成一个通过 remote 方法获取对结果 url 的请求。

下面是REST接口的方法(服务器端是java

@Path("/user")
public interface UserResource {

    @GET
    @Path("/registered/email/{value}")
    public boolean isRegistered(@PathParam("value") String value);
}

下面是要验证的输入字段的样子

<form id="registerForm" action="/register" method="POST">
    <input class="form-control" id="email" name="email" type="email" value='${email}' required/>
    ...
</form>

然后是jQuery验证脚本;

$('body #registerForm').validate({
    rules : {
        'email': {
            required: true,
            email: true,
            remote: "/user/registered/email/" + $(this).find('#email').val()
        },
    },
    messages : {
        'email': {
            required: 'Please enter your email address',
            email: 'Please provide a valid email address',
            remote: 'Email has already been taken',
        },
    },
});

请注意传递给 remote 方法的值是简单的 REST url 因为根据 http://jqueryvalidation.org/remote-method/,默认请求 typeGET... 另请注意如何未指定 dataTypedata,因为在这种情况下不一定需要它们。

目标: ... 现在,假设用户输入的电子邮件是 username@email.com 我通常希望结果 url 如下所示;

http://localhost:8080/user/registered/email/username@email.com

问题: ...但是这就是我得到的;

http://localhost:8080/user/registered/email/?email=username@email.com

问题: ... 注意 url 中 username@email.com 之前的 ?email= ...我想知道为什么 $(this).find('#email').val() 的结果被连接为查询参数?...有人可以向我解释为什么会这样吗?...还有我该如何解决这个问题?

谢谢。

您正在向网站上看起来像文件夹或位置的内容发出获取请求。您需要提供一个执行检查的脚本。所以你的遥控器 url 应该类似于“/user/registered/email/check_email.php”.

此外,GET 请求的整体思路是将参数作为 name/value 对传递,并在“?”之后添加到查询字符串中。分隔器。参见 http://www.w3schools.com/tags/ref_httpmethods.asp。您没有提供实际的远程脚本,也没有为您的值提供参数名称,所以您只得到 url + "?" + 你的价值。

最后,我建议您使用 POST 方法。在您提供 link 的资源中,查看第二个示例。它向您展示了如何指定 POST.

这一切有意义吗?

QUESTION: ... Notice the ?email= before username@email.com in the url... I wonder why the result of $(this).find('#email').val() is being concatenated as a query param?... Please can somebody explain to me why this is happening?.. And also how do I solve this problem?

默认情况下,查询字符串 ?field="value"&field2="value2".... 正是数据与 GET 请求一起发送的方式。通常,您不会使用 URL 段在服务器端获取此值,只需使用 GET 数组。

The jQuery Validate plugin's remote method uses the same options as jQuery .ajax(). Referring to the .ajax() documentation...

data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

...

processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.


OP Title: JQuery Validation - How to correctly retrieve form field value in “remote” method?

要获取字段的值,只需 select 字段并将其附加到 jQuery .val()。不需要使用$(this).find(...

$('#email').val()

试试这个...

rules : {
    'email': {
        required: true,
        email: true,
        remote: {
            url: "/user/registered/email/" + $('#email').val(),
            processData: false
        }
    },
},

我使用此代码解决了 REST 服务问题:

$("#mailingAddress").rules("add", {
    required: true,
    remote: function () { 
        var r = {
            url: "/Api/Address/ValidateAddressSimple/" + $("#mailingAddress").val(),
            type: "post",
            cache: false,
            dataFilter: function (response)
            {
                return response;
            }
        };
        return r;
    },
    messages: {
        remote: "* not valid"
    }
});

取自此post:

THE GOAL: ... Now, say the email entered by the user is username@email.com I would normally expect the resulting url to look like the following;

http://localhost:8080/user/registered/email/username@email.com

THE PROBLEM: ... but instead here's what I get;

http://localhost:8080/user/registered/email/?email=username@email.com

这里有两个问题。首先是 validate 方法在执行时解析 url 路径——默认情况下不会动态重新检查。当它是 运行 时,基本上在呈现表单时,您的电子邮件输入字段是空的。因此,该路径被解析为 'http://localhost:8080/user/registered/email/' + ''(您开始使用的静态字符串,与空输入字段中的空字符串连接)。

第二个问题是 jQuery.validate 的远程方法默认将验证字段的 'name' 和 'value' 属性作为查询参数发送——当然,这不是REST 做事方式。这些被扁平化为'?email=username@email.com',它被放置在 URL 的其余部分之后,因为它在第一步中被解决了。

要解决第一个问题并构建 REST-worthy 路径,您必须将 URL 构建包装在一个函数中,每次在该输入上请求验证时都会执行该函数。

$('body #registerForm').validate({
    rules : {
        'email': {
            required: true,
            email: true,
            remote: function() {
                return '/user/registered/email/' + $('#email').val()
            }
        }
    }
});

这将导致正确的 REST API url,尽管它仍将附加查询字符串。它看起来像这样:

http://localhost:8080/user/registered/email/username@email.com?email=username@email.com

当然,这很丑陋,但您的 API 可能会默默地忽略查询字符串,并按预期执行。

但是为了更干净,更RESTful url,您需要重置ajax调用的数据属性。为此,您可以让第一步中的远程函数 return 成为一个对象,将之前的 url 字符串作为 url 参数,并将数据参数设置为空字符串。

$('body #registerForm').validate({
    rules : {
        'email': {
            required: true,
            email: true,
            remote: function() {
                return {
                    url: '/user/registered/email/' + $('#email').val(),
                    data: ''
                }
            }
        }
    }
});

这将产生所需的结果,RESTful url

http://localhost:8080/user/registered/email/username@email.com