Unsure why variable is undefined. Possible scope issue?

前端 未结 4 639
夕颜
夕颜 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 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);
            }
        });
    
    }
    

提交回复
热议问题