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

私の質問には2つの部分があります。

  1. ファイアバグからのjsコードの結果の値を調べると、ブール型(true / false)ではなく、値が正しくないようですが、コントローラーからのビューでこの値をjsに正しく渡す方法はありますか?

  2. set email valueをコントローラーの変数に呼び出して、ビューの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 に答える