使用jQuery验证插件,我一直在尝试检索表单的输入字段值,将其与一些url前缀连接以生成REST URL,然后通过远程方法向生成的URL发出GET请求.
下面是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',
},
},
});
请注意传递给远程方法的值如何只是REST URL,因为根据http://jqueryvalidation.org/remote-method/,默认请求类型是GET …还要注意未指定dataType和数据,因为在这种情况下不一定需要它们.
目标:
…现在,假设用户输入的电子邮件是username@email.com我通常希望生成的URL看起来如下所示;
HTTP://本地主机:8080/user/registered/email/username@email.com
问题:
……但是这就是我得到的;
HTTP://本地主机:8080 /用户/注册/电子邮件/ email=username@email.com
问题:…请注意url中的?email = before username@email.com …我想知道为什么$(this).find(‘#email’).val()的结果被串联作为查询param?…有人可以向我解释为什么会这样吗?还有我如何解决这个问题?
谢谢.
最佳答案
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使用与jQuery .ajax()相同的选项.参考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. SeeprocessData
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?
要获取字段的值,只需选择字段并将其附加到jQuery .val().没有必要使用$(this).find(…
$('#email').val()
试试这个…
rules : {
'email': {
required: true,
email: true,
remote: {
url: "/user/registered/email/" + $('#email').val(),
processData: false
}
},
},