[英]Declaring global variable not working (returning undefined)
我已經進行了基本設置,而我的問題是我的函數load_heat2
locations_map
變量。 我在下面指出了未定義的位置:
//declare global variables
var full_map;
var locations_map;
function callIndex() {
$(document).ready(function() {
//call some functions
load_map();
load_test_map2();
super_test_map();
load_heat2();
});
$.ajax({
url: 'php/get_map_tables.php',
type: 'POST',
dataType: 'JSON',
data: {
client_id: client_id, //defined elsewhere
},
success: function(data) { //this gives me the correct data in the right variables
var locations_map = data[0].locations_map;
var full_map = data[0].full_map;
}
});
function load_heat2(){
console.log(locations_map); //this yields undefined
}
} //end of callIndex function
我試圖避免將所有內容包裝在AJAX /成功函數中,所以我需要全局變量才能正常工作。
謝謝。
您在成功聲明中聲明了一個名為locations_map的局部變量
$.ajax({
url: 'php/get_map_tables.php',
type: 'POST',
dataType: 'JSON',
data: {
client_id: client_id, //defined elsewhere
},
success: function(data) { //this gives me the correct data in the right variables
**var** locations_map = data[0].locations_map;
var full_map = data[0].full_map;
}
您正在ajax函數中重新聲明兩個變量。
var full_map;
var locations_map;
這是將它們聲明為全局,但是當您在此處設置它們時
success: function(data) { //this gives me the correct data in the right variables
var locations_map = data[0].locations_map;
var full_map = data[0].full_map;
}
它成為本地的。 為了使它們保持全球性,您需要刪除
var
所以看起來像
success: function(data) { //this gives me the correct data in the right variables
locations_map = data[0].locations_map;
full_map = data[0].full_map;
}
獲得ajax請求的響應后,調用load_heat2()函數。 同樣,像其他答案所指出的那樣,刪除兩個變量的“ var”。
//declare global variables
var full_map;
var locations_map;
function load_heat2(){
console.log(locations_map); //this yields undefined
}
function callIndex() {
$(document).ready(function() {
//call some functions
load_map();
load_test_map2();
super_test_map();
});
$.ajax({
url: 'php/get_map_tables.php',
type: 'POST',
dataType: 'JSON',
data: {
client_id: client_id, //defined elsewhere
},
success: function(data) { //this gives me the correct data in the right variables
locations_map = data[0].locations_map;
full_map = data[0].full_map;
load_heat2();
}
});
} //end of callIndex function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.