javascript - 如何在 JavaScript 中使用全局变量?

标签 javascript html scope global-variables

我想更改顶部 ajax 表单中的全局变量并在底部 ajax 表单中使用它。 当我这样做时,这不起作用:

var xGlobalTitle; //global variable that I want to use
$.ajax({
    type: 'GET',
    url: '/Home/postInformationofConferenceTitle',
    dataType: "JSON",
    success: function (data) {

            xGlobalTitle = data.xglobalTitle; //I want to change the value of the variable in here.

    }
})


    alert(window.xGlobalTitle); //And I want to use this value in here
    $.post("/Home/selectRooms", { xtitle: xGlobalTitle }, function (data) {

            var ndx = 0;
            $.each(data.xroom_name, function (key, value) {

                var Xroom_name = data.xroom_name[ndx];
                var Xroom_plan = data.xroom_plan[ndx];

                var column =
                  ('<tr>' +
                    '<td>' +
                    '<div class="img-container">' +
                    '<img src="../../assets/img/room-plan/' + Xroom_plan + '" alt="..." id="imgsrc">' +
                    '</div>' +
                    '</td>' +
                    '<td id="imgname">' + Xroom_name + '</td>' +
                    '<td class="text-right">' +
                    '<a href="#" class="btn btn-simple btn-warning btn-icon edit" data-toggle="modal" data-target="#myModal"><i class="fa fa-edit"></i></a>' +
                    '<a href="#" class="btn btn-simple btn-danger btn-icon remove" ><i class="fa fa-times"></i></a>' +
                    '</td>' +
                    '</tr>');

                document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;

                ndx++;

            });

        });

我该怎么做。在这方面有没有人会支持我?

最佳答案

这将不起作用,因为 ajax 是异步的。无法确定第一个 ajax 何时会成功

因此,为了在第二个 ajax 中使用该值,您需要等到第一个 ajax 成功。这个问题可以通过链接所有 ajax 或使用 Promise & .then

来解决

此外,jquery ajax.done 方法也很有用。将 $.post 放入 .done 回调函数

var xGlobalTitle; //global variable that I want to use
$.ajax({
    type: 'GET',
    url: '/Home/postInformationofConferenceTitle',
    dataType: "JSON",
    success: function (data) {
        xGlobalTitle = data.xglobalTitle; //I want to change the value of the variable in here.
    }
}).done(function(data){
    alert(window.xGlobalTitle)
    $.post("/Home/selectRooms", { xtitle: xGlobalTitle }, function (data) {
     //rest of the code

    })

})

关于javascript - 如何在 JavaScript 中使用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49332121/

相关文章:

JavaScript 点击不工作

javascript - 解析cloudcode beforeSave 获取预更新对象

javascript - 如何使用两个单选按钮显示隐藏两个文本框

javascript - 将局部变量传递给回调函数

python-2.7 - 访问派生类中的基类属性 - 在 "class scope"

javascript - React如何更新n层以上父组件的状态

javascript - 使用 angularjs 使用属性检查取消选中复选框

html - 使 anchor (按钮)适合与其旁边的文本相同的高度

html将页面分成两列并将内容从第一列溢出到第二列

javascript - 状态设置方法没有影响主对象 - ReactJS