使用JavaScript变量外成功功能 [英] Use javascript variable outside success function

查看:105
本文介绍了使用JavaScript变量外成功功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用jQuery验证验证电子邮件。但一个变量,其值在成功的功能被改变是不是外面访问。它可以与异步=假做,但破坏了Ajax的目的。

下面是code:

  $。validator.addMethod(verifyemail',功能(价值要素){
    $阿贾克斯({
        键入:POST,
        网址:$ .app.urls('BASE_URL')+'账户/ check_email',
        数据:{电子邮件:值},
        成功:函数(MSG){
            //如果邮件存在,响应设置为true
            如果(msg.status =='假')
                回应= FALSE;
            其他
                回应= TRUE;
        }
    })
    执行console.log(响应);
    返回响应;
}, 电子邮件已经被采取);
 

解决方案

您不能设置值这样的异步函数。在此工作的方式是,响应将被设置为一个值。那么,你的异步Ajax调用将火熄灭,只要它触发了下面的Ajax调用将执行code中的其余部分。一旦Ajax调用返回时,code。在成功回调将被执行。最有可能的,这时候你的验证函数将完成执行。

由于您使用该Ajax调用的验证器,你想串联运行这个,因为验证取决于你的Ajax调用的结果。你可以通过设置异步做到这一点:假

下面是异步回调一个有用的资源,他们是如何工作的:

HTTP://blog.parse .COM / 2013/01/29 /什么那么大,约-JavaScript的承诺/

和另一个覆盖jQuery的AJAX功能异步VS同步:

<一个href="http://net.tutsplus.com/tutorials/javascript-ajax/event-based-programming-what-async-has-over-sync/" rel="nofollow">http://net.tutsplus.com/tutorials/javascript-ajax/event-based-programming-what-async-has-over-sync/

I have used jquery validation to validate email. But the variable whose value is changed in success function is not accessible outside it. It can be done with async=false, but that destroys the purpose of Ajax.

Below is the code:

$.validator.addMethod('verifyemail',function(value,element){        
    $.ajax({
        type: "POST",
        url : $.app.urls('base_url')+'account/check_email',
        data: {'email' : value},
        success: function(msg){
            //If email exists, set response to true
            if( msg.status == 'false' )
                respond = false;
            else
                respond = true;
        }
    })
    console.log(respond);
    return respond;
}, "Email is Already Taken");

解决方案

You can't set the value in an asynchronous function like that. The way in which this works is that respond would be set to a value. Then your asynchronous ajax call would fire off, as soon as it fires off the rest of the code below your ajax call would execute. Once the ajax call returns, the code in the success callback will be executed. Most likely, by this time your validator function would have finished executing.

Since you're using this ajax call in a validator, you would want to run this in series since the validation depends on the result of your ajax call. You could accomplish this by setting async: false.

Here is a useful resource on asynchronous callbacks and how they work:

http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/

And another covering jQuery's AJAX function async vs sync:

http://net.tutsplus.com/tutorials/javascript-ajax/event-based-programming-what-async-has-over-sync/

这篇关于使用JavaScript变量外成功功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆