Javascript variable being reset when it shouldn't
I have a function I'm calling that loads configuration files and I need to check if there is any data returned, if not I need to alert that the configuration file does not exist.
Here is my code.
// Get JSON data from server
result = false;
function loadData(id) {
$.get("modules/device/loadConfigurationData.php", {
id : id
}, function(response) {
for (var i =0; i < response.length -1; i++)
if (response[i])
{
settings[response[i].setting_name] = response[i].setting_value;
result = true;
}
else
{
result = false;
}
}, 'json');
}
And here are the functions that load the configuration files. NOTE that configuration files do dexist for CONFIG 1 and CONFIG 2, but not CONFIG 3 and CONFIG 4.
// Load Configuration 1
function config1() {
loadData(1)
alert(result);
if (result)
{
alert('CONFIG 1 Loaded');
configurationLoaded = true;
}
else
{
alert('CONFIG 1 does not exist.');
}
}
// Load Configuration 2
function config2() {
loadData(2)
alert(result);
if (result)
{
alert('CONFIG 2 Loaded');
configurationLoaded = true;
}
else
{
alert('CONFIG 2 does not exist.');
}
}
// Load Configuration 3
function config3() {
loadData(3)
if (result)
{
alert('CONFIG 3 Loaded');
configurationLoaded = true;
}
else
{
alert('CONFIG 3 does not exist.');
}
result = false;
}
// Load Configuration 4
function config4() {
loadData(4)
alert(result);
if (result)
{
alert('CONFIG 4 Loaded');
configurationLoaded = true;
}
else
{
alert('CONFIG 开发者_运维问答4 does not exist.');
}
}
This should load the configuration data if data exist, otherwise it should return false and display the alert, letting the user know that the configuration file doesn't exist. For some reason the result variable is getting reset and making it not work.
Any help would be greatly appreciated.
This won't work because get
is run asynchronously. So basically your result variable would most likely be alerted before the result
variable is set in the callback.
loadData(2); would still be loading.
alert(result); this would be called before result is populated.
精彩评论