【问题标题】:Applying a Global Variable to a $.getjson request URL将全局变量应用于 $.getjson 请求 URL
【发布时间】:2019-03-13 03:59:23
【问题描述】:

所以我无法让我的 getJSON 请求将地址的全局变量传递到 URL。我在谷歌方法下面包含了通过它的 API 获取所述地址的方法,然后我将其设置为全局变量 = globalStringAddress。此功能在提示用户同意位置共享后出现。

var map, infowindow, globalStringAddress




    function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 38.907, lng: -77.036},
        zoom: 10
      });
      var infowindow = new google.maps.InfoWindow;
      var geocoder = new google.maps.Geocoder;

    //   // Try HTML5 geolocation.
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          console.log(position.coords.latitude + ", " + position.coords.longitude); 
          //  console.log(poslat + ", " + poslng);
           var latlng = {lat: pos.lat, lng: pos.lng};
           geocoder.geocode({'location': latlng}, function(results, status) {
        if (status === 'OK') {
          if (results[0]) {
            map.setZoom(11);
            var marker = new google.maps.Marker({
              position: latlng,
              map: map
            });
            globalStringAddress = results[0].formatted_address
            console.log("address is : "+ globalStringAddress);
            infowindow.setContent(results[0].formatted_address);
            infowindow.open(map, marker);
            var globalStringAddress = globalStringAddress.replace(/[\s]/g, '+').replace(/[,]/g, '%2C');    
            //var civicAPI ="https://www.googleapis.com/civicinfo/v2/representatives?address="+globalStringAddress+"&key=AIzaSyBwA2-va1J2oaO3IhPn2xqItnyUyhkfkqk";
            console.log(globalStringAddress);




          } else {
            window.alert('No results found');
          }
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
      });



          infowindow.setPosition(pos);
          infowindow.setContent('Cool House Loser');
          infowindow.open(map);
          map.setCenter(pos);
        }, function() {
          handleLocationError(true, infowindow, map.getCenter());
        });
      } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infowindow, map.getCenter());
      }
      console.log("address is : "+ globalStringAddress)
    }
    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
      infoWindow.setPosition(pos);
      infoWindow.setContent(browserHasGeolocation ?
                            'Error: The Geolocation service failed.' :
                            'Error: Your browser doesn\'t support geolocation.');
      infoWindow.open(map);
    }

问题出现在 getJSON 请求中。我无法让 globalStringAddress 变量以允许其执行的方式传递到 URL。我可能应该提到我已经在 initMap 函数中对其进行了一些编辑,试图使其对 url 更友好,但结果始终是https://www.googleapis.com/civicinfo/v2/representatives?address=[object%20Object]&key=xxx

$(document).ready(function(globalStringAddress) {
  $("#officials").click(function(globalStringAddress){
      $.getJSON("https://www.googleapis.com/civicinfo/v2/representatives?address="+globalStringAddress+"&key=xxx", function(result){

        window.localStorage.setItem('Senator1', result.officials[2].name),
        window.localStorage.setItem('Senator2', result.officials[3].name),
        Senator1= result.officials[2].name,
        Senator2= result.officials[3].name,
        $("#lobby").append(
        "You're Senators are " + result.officials[2].name + " & " + result.officials[3].name,
        " and you're Representative is " + result.officials[4].name),
       // console.log(result.officials[3].channels[0].id),
        $.each(result.officials , function(k , v){
          $("#lobby").append(
            //  v.name +' - '+ v.address[0].line1 + " and ",

        );
      });
    });
  });
});

这是定位问题吗?我应该将 globalStringAddress 声明为字符串吗?这是同步问题吗?任何朝正确方向的箭头都非常感谢,因为我对调制有点陌生

【问题讨论】:

  • 当您使用function(globalStringAddress) 时,globalStringAddress 将使用索引或对象再次定义.. 所以从function(globalStringAddress) 中删除globalStringAddress 准备好并单击功能
  • 这使得它在 URL (googleapis.com/civicinfo/v2/…) 中未定义,通过这两个函数传递它是我在 globalStringAddress 位置中获得任何类似内容的唯一方法
  • 它可能是未定义的,因为在执行 initMap 之前页面加载 globalStringAddress 是未定义的?同样,我的调制经验才刚刚开始,但我在 initMap 中将正确的地址详细信息记录到控制台
  • 您可以从undefined 开始,这意味着您的变量仍未在其他函数中更新
  • 所以问题出在initMap函数的结构上?我应该把它作为页面做的第一件事,以便在较低的功能中识别它吗?

标签: javascript jquery json get global-variables


【解决方案1】:

使用JSON.stringify:

$.getJSON("https://www.googleapis.com/civicinfo/v2/representatives?address=" + JSON.stringify(globalStringAddress) + "&key=xxx", function(result) {...});

【讨论】:

  • 不,这会导致 Uncaught TypeError: Converting circular structure to JSON 出错
  • 未捕获的类型错误:在 HTMLButtonElement. (app.html:219) 处的 HTMLButtonElement. (app.html:219) 处将循环结构转换为 JSON.stringify () HTMLButtonElement.dispatch (jquery-1.9.1.min .js:3) 在 HTMLButtonElement.v.handle (jquery-1.9.1.min.js:3)
  • 抱歉,顺便说一句。不确定如何重新格式化这些 cmets
【解决方案2】:

所以我通过将较低的 jQuery 嵌套到 initMap() 函数中来实现这一点。我认为问题在于我在函数内声明 globalStringAddress 变量全局的缺乏光泽的方法? idk 但它现在可以很好地填充到 URL 中

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 2011-03-14
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 2017-10-23
    相关资源
    最近更新 更多