简体   繁体   English

Parsley远程和服务器端验证(无法从json对象获取内容)

[英]Parsley Remote and Server Side Validation (can't get content from json object)

I am trying to validate if an email already exists in our database. 我正在尝试验证我们的数据库中是否已存在电子邮件。 I always get a 200 status code from the Ajax Request, but I get the body of the request that looks like this. 我总是从Ajax请求中获得200状态代码,但是我得到的请求主体看起来像这样。 Result =1 if that email does not exists and is available (the form should return true) and Result = 0 if that email already exists in the database (the from should return false and not validate). 如果该电子邮件不存在并且可用(结果应该返回true),则Result = 1;如果该电子邮件已经存在于数据库中(则from应该返回false并且不验证),则Result = 0。 However I keep geting data undefined in the console. 但是,我一直在控制台中获取未定义的数据。 Seems like I don't know how to pass the json object to the function. 好像我不知道如何将json对象传递给函数。

I'll buy a beer to anyone that can help me figure this out. 我会买啤酒给任何可以帮助我解决这个问题的人。 Thank you. 谢谢。

JSON RESPONSE JSON响应

 id: "1c29da8e-ca94-4ea4-a69f-f0af15f54bf5", redirectPage: "/public/actionStatus.jsp", errorText: "",…} action: "/check.douserEmailAvailable" data: {} errorCode: "" errorText: "" id: "1c29da8e-ca94-4ea4-a69f-f0af15f54bf5" redirectPage: "/public/actionStatus.jsp" result: "1" text1: "" text2: "" text3: "" text4: "" text5: "" 

JQUERY and HTML JQUERY和HTML

 $(document).ready(function(){ window.Parsley.addAsyncValidator('mycustom', function (data) { if (data.result == 1) { console.log("does not exist"); return true; } else { console.log("already exist"); return false; } }, '/check.do?action=userEmailAvailable&ajax=1'); $('#userReg').parsley(); }); 
  <input type="email" name="userEmail1" data-parsley-remote data-parsley-remote-options='{ "type": "POST", "data": { "token": "value" } }' data-parsley-remote-validator='mycustom' id="userEmail1" value="" required /> 

The first argument passed to your asynch validator is xhr , not data . 传递给异步验证器的第一个参数是xhr ,而不是data

You can use $.parseJSON(xhr.responseText) , or xhr.done(function(json){...}) , etc... to do what you are trying to do. 您可以使用$.parseJSON(xhr.responseText)xhr.done(function(json){...})等来完成您想做的事情。

Got it working, If anyone has issues in the future. 如果任何人将来遇到问题,都可以使用。

 $(document).ready(function(){ window.Parsley.addAsyncValidator('emailvalidation', function (data) { var myResponseText = data.responseText; var obj = jQuery.parseJSON(myResponseText); if (obj.result == 1) { return true; } else { return false; } }, '/check.do?action=userEmailAvailable&ajax=1'); $('#userReg').parsley().on('form:success', function() { var formData = $("#userReg").serializeArray(); var action = "<%=pdo.getRegistrationData().registrationType.toString()%>"; $.post("/userRegistration.do?action="+ action +"&ajax=1", formData, function(data) { window.location.href = data.redirectPage; }); }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM