gpt4 book ai didi

jQuery 不能在主范围内使用变量

转载 作者:行者123 更新时间:2023-12-01 08:05:47 25 4
gpt4 key购买 nike

我有user_permissions变量,我定义了该变量供全局使用,在 post 方法上设置此变量后,打印该变量没有问题,但是在下面的许多行中使用此变量后,我得到 null结果???

jQuery(最少代码):

var user_permissions = null;
$(document).ready(function(e) {
$.post('model/controller.php' ,{ username:iId_username , postaction:'getUserPermission' },
function(data){
user_permissions=0;
user_permissions = data.user_permissions;
console.log(user_permissions); // RESULT is : {"user_permissions":"8"}
},'json');
$.each(listPermissions, function(i, item) {
if ( user_permissions == listPermissions[i].id ) selected = "selected='selected'"; else selected = '';
console.log(user_permissions); // RESULT is : null
selectElement += "<option value='" + listPermissions[i].id + "' "+ selected + ">" + listPermissions[i].permission_title + "</option>";
});

});

我的代码有什么问题吗?

最佳答案

这是因为 .post() 是异步的,您的 .each() 在您的帖子完成之前就已执行,

您需要在post回调中移动.each()

$.post('model/controller.php', {
username: iId_username,
postaction: 'getUserPermission'
},

function (data) {
user_permissions = 0;
user_permissions = data.user_permissions;
console.log(user_permissions); // RESULT is : {"user_permissions":"8"}
$.each(listPermissions, function (i, item) {
if (user_permissions == listPermissions[i].id) selected = "selected='selected'";
else selected = '';
console.log(user_permissions); // RESULT is : null
selectElement += "<option value='" + listPermissions[i].id + "' " + selected + ">" + listPermissions[i].permission_title + "</option>";
});
}, 'json');

关于jQuery 不能在主范围内使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16776007/

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