I want to use a local variable as a global variable and I was told the way to do so is to create the variable outside the function, like this:
var foo = null;
function bar() {
foo = 3;
}
console.log(foo);
However the foo logs null, instead of 3. This is the simplest example I could think of, but mainly I want to be able to use the data from a variable I created in a function throughout my whole script.
What am I doing wrong?
Same question in an Ajax request :
var status = null;
.ajax({
url: myUrl,
success: function (data) {
status = data.status; //returns a string
console.log(status); // it works, I get the string
},
dataType: 'jsonp'
});
console.log(status); // still null
You need to call the function first like this.
var foo = null;
function bar() {
foo = 3;
}
bar();
console.log(foo);
Your best bet here is to call a function that logs the data after the ajax runs. In this example I created a function called logit()
which is called in the ajax request state.
var status = null;
$.ajax({
url: myUrl,
success: function (data) {
status = data.status; //returns a string
console.log(status); // it works, I get the string
logit();
},
dataType: 'jsonp'
});
function logit(){
console.log("logit(): " + status);
}
The reason you are getting null is because this is the order that your code is running:
status
to null status
which is still null
because the success callback hasn't run yet status
is set to data.status
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.