Javascript全局变量简单解决方案

时间:2016-04-22 16:42:58

标签: javascript jquery function global-variables

我正在尝试学习javascript,并且由于通过多个函数处理变量而遇到了墙。

浏览文档和stackoverflow大多数投票答案后,与全局变量以及如何通过多种功能有效地使用它们相关。

我发现很少甚至没有简单的解决方案。

任何善良的人都能够纠正这段完整的代码如何正常工作?

  

变量“ttl”和“msg”需要从“ajax”函数传递到“notify”函数

<script src="js/jquery.js"></script>
<script src="js/bootstrap-notify.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        // Global variables ttl and msg needed ?
        var ttl = null;
        var msg = null;

        // Make an ajax call to json file.
        $.ajax({
            url: "lastorder.json",
            dataType: "json",
            // Parse title and message from json.
            success: function(data) {
                ttl = data.title;
                msg = data.message;
            }
        });
        // Notify function displays a title and message that was parsed from json file
        $.notify({
            icon: 'img/avatar.jpg',
            title: ttl,
            message: msg
        },{
            type: 'minimalist',
            delay: 3000,
            icon_type: 'image',
            template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
                '<img data-notify="icon" class="img-circle pull-left">' +
                '<span data-notify="title">{1}</span>' +
                '<span data-notify="message">{2}</span>' +
            '</div>'
        });

    });
</script>

2 个答案:

答案 0 :(得分:1)

如果您想尝试@MikeC解决方案:

$(document).ready(function () {
        // Global variables ttl and msg needed ?
        var ttl = null;
        var msg = null;

        // Notify function displays a title and message that was parsed from json file
        function notify(data) {

            ttl = data.title;
            msg = data.message;

            $.notify({
                icon: 'img/avatar.jpg',
                title: ttl,
                message: msg
            }, {
                type: 'minimalist',
                delay: 3000,
                icon_type: 'image',
                template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
                '<img data-notify="icon" class="img-circle pull-left">' +
                '<span data-notify="title">{1}</span>' +
                '<span data-notify="message">{2}</span>' +
            '</div>'
            });

        }

        // Make an ajax call to json file.
        $.ajax({
            url: "lastorder.json",
            dataType: "json",
            // Parse title and message from json.
            success: notify
        });

    });

答案 1 :(得分:0)

如果要从ajax请求返回响应,则可以在ajax请求成功执行后获取此数据。 由于ajax是异步调用,因此等待响应的代码将在收到响应时执行。 因此,您不会通过通知函数中的ajax响应获得准确的值返回。

因此,为了使用由ajax响应返回的值,必须在ajax的success()方法中调用notify函数。

refer this SO question