Unsure why variable is undefined. Possible scope issue?

前端 未结 4 635
夕颜
夕颜 2021-01-26 13:28

If you look at the function below, on line 11 where it alert(template);. It prints undefined. If I alert(template); inside the ajax succes

相关标签:
4条回答
  • 2021-01-26 13:52

    The success function is a callback. The javascript engine makes the request to the server, and when the server responds to the data, then it runs the success function and you have the data, so the success function is run after your if statement at the end, even though its defined beforehand.

    Javascript code is run inside of an Event Loop, all $.ajax is doing is starting an asynchronous event and specifying what to do when that event occurs.

    0 讨论(0)
  • 2021-01-26 14:00

    template isnt defined until your ajax request is completed.

    thats why it shows fine in the success function.

    not sure what framework that is ( JQuery I presume ) but you need to do the callback in the ajax success function.

    0 讨论(0)
  • 2021-01-26 14:04

    No, it's not a scope issue, it's a timing issue.

    The AJAX call is asynchronous, so the success callback runs later, when the response arrives. The variable is simply not set yet, when you try to use it.

    You can't return the value from the function, as the success callback never runs until you have exited the function. Always use the callback that is sent to the function:

    function load_template(path, data, callback){
    
        $.ajax({
            url: path,
            success: function(uncompiled_template){
                var template = Handlebars.compile(uncompiled_template);
                callback(template, data);
            }
        });
    
    }
    
    0 讨论(0)
  • 2021-01-26 14:07

    ajax is asynchronous. to explain in simple terms: ajax works like it runs on a separate "thread", processing in the background while your code continues.

    by the time you called load_template(), it alerts after $.ajax() was called but before the template was returned thus undefined.

    what you can do is this so everything runs after a success has been returned:

    function load_template(path, data, callback){
    
        $.ajax({
            url: path,
            success: function(uncompiled_template){
                var template = Handlebars.compile(uncompiled_template);
    
                alert(template);    
    
                if(callback){
                    callback(template, data);
                }else{
                    return template(data);
                }
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题