我正在研究如何将变量的值推送到 json 函数之外。我正在将 Google map 和 Instagram 的 API 集成在一起,因此我将经度和纬度坐标传递给 glat,将 glng 传递给 var url(这在 google 函数之外)。目前我正在使用 PHP,不太熟悉 json。
var glat;
var glng;
//Google maps latitude and coordinates
$.getJSON(mapurl, function(google){
glat = google.results[0].geometry.location.lat;
glng = google.results[0].geometry.location.lng;
console.log('<?php echo urlencode($_GET['location']);?>');
console.log(glat);
console.log(glng);
//return glat;
});
var url = "https://api.instagram.com/v1/media/search?lat=" + glat + "&lng=" + glng + "&distance=1000&client_id=<?php echo $client_id; ?>&count=40&callback=?";
//This pulls the instagram images
console.log(url);
//Instagram Feed
$.getJSON(url, function (response) {
//http://techmonks.net/instagram-using-the-api/
for(var i = 0; i < 40; i++){
$("#feed ul").append("<li><a target='_blank' href='"+response.data[i].link +"'><img src='"+response.data[i].images.low_resolution.url+"'/></a></li>");
}
});
最佳答案
$.getJSON
导致异步 XMLHttpRequest。由于这是异步的,因此当您尝试定义 URL 以指向 Instagram 时,不会定义 lat 和 lng。
var glat;
var glng;
//Google maps latitude and coordinates
$.getJSON(mapurl, function(google){
glat = google.results[0].geometry.location.lat;
glng = google.results[0].geometry.location.lng;
console.log('<?php echo urlencode($_GET['location']);?>');
console.log(glat);
console.log(glng);
var url = "https://api.instagram.com/v1/media/search?lat=" + glat + "&lng=" + glng + "&distance=1000&client_id=<?php echo $client_id; ?>&count=40&callback=?";
console.log(url);
$.getJSON(url, function (response) {
//http://techmonks.net/instagram-using-the-api/
for(var i = 0; i < 40; i++){
$("#feed ul").append("<li><a target='_blank' href='"+response.data[i].link +"'><img src='"+response.data[i].images.low_resolution.url+"'/></a></li>");
}
});
});
关于javascript - 将 json 值作为函数外部的变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32443632/