【问题标题】:Wrap a getJSON into a function to be able to return a value将 getJSON 包装到函数中以便能够返回值
【发布时间】:2012-12-16 17:25:44
【问题描述】:

我编写的函数有一些问题。 我想将整个事情包装到一个名为 myClosestCity 的函数中,该函数根据提供用户 IP 坐标的 JSON 提要返回城市名称。据我所知,问题出在 getJSON 函数中。 我已经尝试过使用全局变量、getter 和 setter(根本不起作用)以及我能想到的所有谷歌搜索。

顺便说一句,要运行代码,您需要包含来自 Google 地图的脚本: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry

无论如何,这是我的全部代码:

var stavanger = new google.maps.LatLng(58.96998, 5.73311);
var oslo = new google.maps.LatLng(59.91387, 10.75225);
var trondheim = new google.maps.LatLng(63.43051, 10.39505);
var bergen = new google.maps.LatLng(60.39126, 5.32205);

function calcDistance(p1, p2){
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}



$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data) {
myLocation = new google.maps.LatLng(data.geoplugin_latitude,data.geoplugin_longitude);
var distances = new Array();
distances[0] = calcDistance(myLocation, stavanger);
distances[1] = calcDistance(myLocation, oslo);
distances[2] = calcDistance(myLocation, trondheim);
distances[3] = calcDistance(myLocation, bergen);



maxValue = Math.min.apply(this, distances);
var findThisIndex = maxValue + "";
var placeNo = $.inArray(findThisIndex, distances);


if(placeNo == 0) {
    closestCity = "Stavanger";
}

else if (placeNo == 1){
    closestCity = "Oslo";
}

else if(placeNo == 2) {
    closestCity = "Trondheim";
}

else if(placeNo == 3){
    closestCity = "Bergen";
}

else {
    closestCity = "Ukjent"; // Unknown in Norwegian
}

alert(closestCity);
  });

更新:这是我想返回的最接近的城市变量!

【问题讨论】:

  • 你到底在问什么有点令人困惑......你是否试图让异步 getJSON 表现得像一个同步函数? (阻止调用函数直到它可以返回其结果。)
  • 感谢您的快速回复。我不确定我想怎么做,但我想将所有代码包装到一个函数中并返回最接近的城市变量。我现在看到有可能将大量代码移出 getJSON 函数。我会试一试,如果成功了,我会回复。对我自己的凌乱代码有点困惑。
  • 马上开始 ..仅基于标题,您正在遵循 AJAX 的常见错误路径。在请求的成功回调中使用 AJAX 数据。在不涉及延迟对象的情况下,AJAX 根据定义是异步的,因此您不能将函数包装在它周围并返回数据
  • 运行良好。你只是想构造代码吗?

标签: javascript jquery tidesdk


【解决方案1】:

有点晚了,但我会这样做,通过返回一个承诺:

function myClosestCity() {
    var def = $.Deferred();
    $.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data) {
        var myLocation = new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude),
            distances = [calcDistance(myLocation, places.stavanger),
                         calcDistance(myLocation, places.oslo),
                         calcDistance(myLocation, places.trondheim),
                         calcDistance(myLocation, places.bergen)
                                            ],
            minValue = distances.indexOf(Math.min.apply(Math, distances).toString());
        def.resolve(Object.keys(places)[minValue]);
    });
    return def.promise();
}

你会这样使用它:

myClosestCity().done(function(city) {
    console.log(city); // returns the closest city
});

这是DEMONSTRATION

【讨论】:

    【解决方案2】:

    如果我了解您想要执行以下操作:

    var myClosestCity = function(fn){
        $.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data){
           /* calculate closestCity */
           ...
           /* pass closestCity to the callback */
           fn(closestCity);
        });
    };​
    

    由于$.fn.getJSON 是一个异步函数,您可以传递一个回调函数(fn),该函数将在服务器响应并完成closestCity 的计算后调用。

    您可以通过以下方式使用它传递回调函数。

    myClosestCity(function(closestCity){
      alert(closestCity);
    });
    

    【讨论】:

      【解决方案3】:

      您可以定义您的功能,然后等待服务器响应,然后使用您最接近的城市。 你可以这样修改你的代码:

      var myClosestCity = function(callback) {
          var stavanger = new google.maps.LatLng(58.96998, 5.73311);
          var oslo = new google.maps.LatLng(59.91387, 10.75225);
          var trondheim = new google.maps.LatLng(63.43051, 10.39505);
          var bergen = new google.maps.LatLng(60.39126, 5.32205);
      
          function calcDistance(p1, p2) {
              return (google.maps.geometry.spherical.computeDistanceBetween(p1,      p2) / 1000).toFixed(2);
          }
      
      
          $.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data) {
              myLocation = new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude);
              var distances = [];
              distances[0] = calcDistance(myLocation, stavanger);
              distances[1] = calcDistance(myLocation, oslo);
              distances[2] = calcDistance(myLocation, trondheim);
              distances[3] = calcDistance(myLocation, bergen);
      
      
      
              maxValue = Math.min.apply(this, distances);
              var findThisIndex = maxValue + "";
              var placeNo = $.inArray(findThisIndex, distances);
      
      
              if (placeNo === 0) {
                  closestCity = "Stavanger";
              }
      
              else if (placeNo == 1) {
                  closestCity = "Oslo";
              }
      
              else if (placeNo == 2) {
                  closestCity = "Trondheim";
              }
      
              else if (placeNo == 3) {
                  closestCity = "Bergen";
              }
      
              else {
                  closestCity = "Ukjent";
              }
      
              if (typeof callback === "function") {
                  callback.call(null, closestCity);
              }
          });
      };
      
      
      //call the function and display the closestCity on callback
      myClosestCity(function(closestCity) {
          alert(closestCity);
      });?
      

      【讨论】:

      • 非常感谢!这似乎工作得很好!我正在从另一个文档中加载它,这非常成功!
      • 很高兴为您提供帮助
      【解决方案4】:

      这里是用html包裹的函数的实现

          <!DOCTYPE html>
          <html>
          <head>
          <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
          <script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>
          <meta charset=utf-8 />
          <title>Test</title>
          </head>
          <body>
      
            <script>
              function myClosestCity(closestCity) {
                alert(closestCity);
              }
      
              function findClosestCity(fnCallback) {
                var stavanger = new google.maps.LatLng(58.96998, 5.73311);
                var oslo = new google.maps.LatLng(59.91387, 10.75225);
                var trondheim = new google.maps.LatLng(63.43051, 10.39505);
                var bergen = new google.maps.LatLng(60.39126, 5.32205);
      
                function calcDistance(p1, p2) {
                  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
                }
      
      
                $.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?", function(data) {
                  myLocation = new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude);
                  var distances = new Array();
                  distances[0] = calcDistance(myLocation, stavanger);
                  distances[1] = calcDistance(myLocation, oslo);
                  distances[2] = calcDistance(myLocation, trondheim);
                  distances[3] = calcDistance(myLocation, bergen);
      
                  maxValue = Math.min.apply(this, distances);
                  var findThisIndex = maxValue + "";
                  var placeNo = $.inArray(findThisIndex, distances);
      
                  if (placeNo == 0) {
                    closestCity = "Stavanger";
                  } else if (placeNo == 1) {
                    closestCity = "Oslo";
                  } else if (placeNo == 2) {
                    closestCity = "Trondheim";
                  } else if (placeNo == 3) {
                    closestCity = "Bergen";
                  } else {
                    closestCity = "Ukjent";
                    // Unknown in Norwegian
                  }
      
                  fnCallback(closestCity);
                });
              }
      
              // When everything loads call the getJSON with handle of my function myClosestCity
              // 
      
              window.onload = function() {
                findClosestCity(myClosestCity);
              };
            </script>
      
      
          </body>
          </html>
      

      演示here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        相关资源
        最近更新 更多