【发布时间】:2017-07-17 13:30:57
【问题描述】:
由于某种原因,我无法访问变量。可能是范围问题,或者时间问题,查不出来。这是我的简化代码:
var endResult = "";
//function loads html into given element.Called as a callback later when google maps direction service is done//
function getResults(){
$.ajax({
url:'foo.php',
data: endResult,
//etc., response loaded asynchronously in div element//
});
}
//when form is submitted
$('#form').submit(function(){
var endResult = "";
//get form data, define variable//
$.post('bar.php',function(data){
var location = data;
//initialize Maps Directions Service//
var directionService = new google.maps.DirectionsService();
//function gets directions, and loads a single value into global variable "endResult"//
function calcRoute(){
var request = {//google maps arguments containing form data//};
directionsService.route(request, function(result, status) {
var endResult = JSON.stringify(result.routes[0].legs[0].distance.value);
console.log(endResult); //Outputs intended value from google maps//
//run function as a callback making sure that "endResult" is not null//
getResults(); //iside this function - value of "endResult" is null, data sent to foo.php is null//
});
}
calcRoute();
}
return false;
});
就是这样,一旦我在该函数中调用 getResults(),endResult 将为空。我确信这很简单,但我无法理解它。
【问题讨论】:
-
只在全局第一次声明 endResult.. 之后你不需要写“var”,因为你每次都声明它是新的。
-
您似乎有在为变量赋值时使用
var的习惯。var声明一个变量。分配给现有变量时不要使用它。
标签: javascript jquery ajax google-maps scope