我对Grails还是很陌生,所以请多多包涵。
我的 View 具有如下的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}
}
和我的 Controller 看起来像:
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
我的问题分为两部分:
不是 bool(boolean) 类型(真/假),并且该值似乎不正确,是否有任何方法可以传递此值
正确地从 Controller View 中的js?
Controller 并在我看来在js之外调用它?
提前致谢。
最佳答案
记住Ajax是异步的-您的if(result)
在发送远程调用后立即执行,而不是在完成时执行。
更好的方法是更改 Controller 操作以返回一些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专家,但您明白了。
关于javascript - Grails从 View 访问 Controller 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954948/