我对Grails很新,所以请耐心等待。
我的观点有javascript代码喜欢这个:
//js code in my View
function validateEmailAndSetEmail(){
var result =${remoteFunction(controller:'myController',action:'validateEmail',update:'responseDiv', params:'\'email=\'+document.getElementById(\'email\').value')};
if (result) { //doSomething}
}
我的控制器看起来像:
def validateEmail = {
def emailToValidate = request.getParameter("email")
def matchingEmailFound = myService.checkEmailAddress(emailToValidate)
if (matchingEmailFound){
render "This email is already in use.<br>If you have already created an account with this email, please try to reset the password from Login page."}
else{
//setEmail to send here
render "This email is not in use. This email will be used as your account email"}
return !matchingEmailFound
我的问题分为两部分:
当我从firebug中检查我的js代码中 result 的值时,它是 不是布尔类型(true / false)并且值似乎不正确,是否有任何方法可以传递此值 从控制器到视图中的js正确吗?
我是否可以将设置的电子邮件值调用到某个变量中 控制器并在我看来在js之外调用?
提前致谢。
答案 0 :(得分:1)
记住Ajax是异步的 - 只要发送了远程调用,就会执行if(result)
,而不是在完成后。{/ p>
更好的方法是更改控制器操作以返回一些JSON数据:
def model = [matchFound:matchingEmailFound]
if(matchingEmailFound) {
model.message = "This email is already in use.<br>If you have already created an account with this email, please try to reset the password from Login page."
} else {
model.message = "This email is not in use. This email will be used as your account email"
}
render (model as JSON)
然后在客户端使用onSuccess
函数而不是更新。
${remoteFunction(controller:'myController',action:'validateEmail',
params:'\'email=\'+document.getElementById(\'email\').value', onSuccess:'checkEmail(e)')};
并定义
function checkEmail(response) {
var r = JSON.parse(response.text);
$('responseDiv').innerHTML = r.message;
if(r.matchFound) {
// do stuff
}
}
我不是JavaScript专家,但你明白了。