开发者

jQuery How to set up a global var problem?

开发者 https://www.devze.com 2023-02-24 10:31 出处:网络
i am tying to set up a global var to be used through my entire script. and as simple as it looks i can\'t get it to work:

i am tying to set up a global var to be used through my entire script. and as simple as it looks i can't get it to work:

get_back = "";  //should be a global var or
var get_back = "";// another开发者_如何学运维 option

$.get('php/get_username.php', { username: userName }, function(data){
    var get_back = data;
    alert(get_back);
});

i want to be able to use the get_back into url: 'http://www.xxx.com/users/' + get_back + ''

any ideas?

Thanks


I'm having difficulty grasping what your code is doing, but try this:

var get_back = ""; //Global Definition

$.get('php/get_username.php', { username: userName },
function(data){
  get_back = data;
  alert(get_back);
});

The difference is that you only use the keyboard "var" once. That way, when it is set later in the function it is the same variable. When you use var, you force a local definition.


Your variable get_back inside the callback is being declared as a local variable, hiding the outside one. Remove var from that inner declaration, turning it into a bog-standard assignment:

var get_back = "";

$.get('php/get_username.php', { username: userName },
function(data){
    get_back = data;
    alert(get_back);
});


Drop the var declaration from inside the callback function:

var get_back = '';

$.get('php/get_username.php', { username: userName }, function(data) {
    get_back = data;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号