1

我对 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

我的问题有两个部分:

  1. 当我从 firebug 检查我的 js 代码中的结果值时,它不是布尔类型(true/false)并且该值似乎不正确,有没有办法将此值正确传递给控制器​​视图中的 js?

  2. 我可以将设置电子邮件值调用到控制器中的某个变量并在我的视图中调用 js 之外的变量吗?

提前致谢。

4

1 回答 1

1

请记住,Ajax 是异步if(result)的——远程调用一发送就执行,而不是在它完成时执行。

更好的方法是更改​​控制器操作以返回一些 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 专家,但你明白了。

于 2012-06-08T20:42:04.963 回答