简体   繁体   English

在成功函数之外使用javascript变量

[英]Use javascript variable outside success function

I have used jquery validation to validate email. 我已经使用jquery验证来验证电子邮件。 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. 可以使用async = false来完成,但这破坏了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. 这种工作方式是将respond设置为一个值。 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. 然后,异步ajax调用将被触发,一旦它执行了您的ajax调用下面的其余代码,则将被执行。 Once the ajax call returns, the code in the success callback will be executed. 一旦ajax调用返回,将执行成功回调中的代码。 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. 由于您正在验证器中使用此ajax调用,因此您将要连续运行此操作,因为验证取决于ajax调用的结果。 You could accomplish this by setting async: false . 您可以通过设置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/ http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/

And another covering jQuery's AJAX function async vs sync: 另一个涵盖jQuery的AJAX函数async vs sync:

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

Ajax call is asynchronous, meaning when you call console.log(respond); Ajax调用是异步的,这意味着当您调用console.log(respond);时。 The variable respond is still not available. 变量response仍然不可用。 If you need to access it outside the success function, you can trigger a custom event and get respond in the event handler. 如果需要在成功函数之外访问它,则可以触发自定义事件并在事件处理程序中获取响应。

And of course, you have to put respond in outer scope. 当然,您必须将响应放在外部范围内。

respond is already a global variable (lack of var keyword), but the asynchronous nature of AJAX means that it won't necessarily be available when the following lines run, so you need to sequence it in one of a few ways respond已经是一个全局变量(缺少var关键字),但是AJAX的异步特性意味着它在以下行运行时不一定可用,因此您需要采用以下几种方式之一对其进行排序

  • Make it synchronous (but the question rules that out) 使它同步(但问题排除了此问题)
  • put the responding code inside of the same anonymous function 将响应代码放入相同的匿名函数中
  • You could also make a while loop that spins until respond is set, but that would probably be a poor solution. 您还可以创建一个while循环,该循环旋转直到设置了response为止,但这可能是一个糟糕的解决方案。

Hope that helped 希望能有所帮助

to access the respond variable you need to either define it in upper scope 要访问响应变量,您需要在上限范围内对其进行定义

$.validator.addMethod('verifyemail',function(value,element){        
    var respond = true; // scope of variable to current function
    $.ajax({
        type: "POST",
        url : $.app.urls('base_url')+'account/check_email',
        async: false,  
        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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM