javascript - 将 json 值作为函数外部的变量传递

标签 javascript json

我正在研究如何将变量的值推送到 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/

相关文章:

json - 拆分字符串并从复杂 JSON 结构中的每个部分修剪已知前缀

PHP 将具有多条记录的 XML 文件转换为 JSON

java - 如何从 OpenAPI 3.0 yaml 文件生成 JSON 示例?

javascript - 读取使用 JavaScript 生成的页面

javascript - Firebase FCM React 项目问题 - firebase-messaging-sw.js 类型错误?

javascript - javascript中的数组过滤数据

php - 编码的 json 被 PostgresQL 损坏/转义?

c++ - 如何在 QT 中解析关联的 JSON 数组?

javascript - 如何打开源api

javascript - 是否可以在javascript中解析对象的所有公共(public)变量?