0
我想訪問名爲locations
的javascript變量,而不是其分配的方法。在其分配的方法外部訪問JavaScript變量
Javascript代碼:
$(document).ready(function() {
var locations;
console.log('document ready');
function initializeMap() {
$.ajax({url: "getlocation.php",
success: function(result){
locations = $.parseJSON(result);
alert(locations);
}
});
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
initializeMap();
});
我怎樣才能獲得JSON解析傳遞給變量,這樣我可以得到它的分配方法之外,並進入循環數據的位置數據?
這裏是最終的程序代碼,解決了我的問題:
$(document).ready(function() {
console.log('document ready');
function initializeMap() {
var locations;
$.ajax({url: "getlocation.php",
success: function(result){
alert(result);
locations = $.parseJSON(result);
alert(locations);
}
});
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
initializeMap();
});
「按引用傳遞」和「按值傳遞」的兩種編程描述的方法傳遞變量到時的行爲條款方法。
試過了,沒有工作:(。仍然是一個可變的路徑是不確定的。 –
u能寫代碼修改後! – Noctisdark
更新的問題。請赫克 –