将变量传递给函数并返回

时间:2016-11-07 21:00:28

标签: jquery ajax variables scope

我试图弄清楚为什么这不起作用。我以为我理解了范围...

var admin_data = false;
function getPlayerAdmin(){
    var formData = {
        'player_id' : $('#post-v').attr('data-val')
    };
    $.ajax({
        type: 'post',
        url: '/popins/player/controls',
        data : formData,
        dataType : 'json',
        success: function(admin_data) {
            if(admin_data.controls.is_admin == true){
                admin_data = true;
            }else{
                admin_data = false;
            }
        }
    });
}
alert(admin_data);

所以基本上admin_data被设置为true,但是当我提醒它时它不会改变它。如何将其传回去?

谢谢!

到目前为止,我现在有了这个:

var admin_data = false;

adminData(function(admin_data) {
    if(admin_data_vals.controls.is_admin == true){
        admin_data = true;
    }else{
        admin_data = false;
    }
});

function getPlayerAdmin(adminData){
    var formData = {
        'player_id' : $('#post-v').attr('data-val')
    };
    $.ajax({
        type: 'post',
        url: '/popins/player/controls',
        data : formData,
        dataType : 'json',
        success: adminData
        },
        error : function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR);
        }
    });
}
alert(admin_data);

第三次尝试:

var admin_data = false;
function getPlayerAdmin(admin_data){
    var formData = {
        'player_id' : $('#post-v').attr('data-val')
    };
    $.ajax({
        type: 'post',
        url: '/popins/player/controls',
        data : formData,
        dataType : 'json',
        success: function(admin_data_vals, admin_data) {
            if(admin_data_vals.controls.is_admin == true){
                admin_data = true;
            }else{
                admin_data = false;
            }
        },
        error : function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR);
        }
    });
}
getPlayerAdmin();
alert(admin_data);

1 个答案:

答案 0 :(得分:1)

你可以在这里做很多事情来解决这个问题,比如promises,deferred objects等等,但是你可以简单地在成功/错误回调中做你的逻辑,如果没有太多的复杂性你需要做什么随着回应。

success: function(adminData) { // Should probably change the parameter name
                               // to not be the same as the variable you are setting
  if (adminData.controls.is_admin == true) {
    admin_data = true;
    alert(admin_data);
  } else {
    admin_data = false;
    alert(admin_data);
  }
}