gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:22:20 25 4
gpt4 key购买 nike

我想更改顶部 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com