【问题标题】:$.getJSON returns unidentified [duplicate]$.getJSON 返回身份不明的 [重复]
【发布时间】:2013-04-02 17:54:48
【问题描述】:

我正在尝试从 Google 地图提供的 JSON 访问持续时间数据。用户输入 2 个邮政编码,我应该显示所用时间。

function getData() {
    var origin = $("#origin_pc").val() + ",australia";
    var destination = $("#dest_pc").val() + ",australia";
    // var origin="3135,australia";
    // var destination="3155,australia";
    url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
    return url;
}

function calculateDistance() {
    // console.log(getData());
    var my_json;
    $.getJSON(getData(), function (json) {
        my_json = json;
    });
    console.log(my_json.routes[0].legs[0].duration.value);
}

这是我的 HTML

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>

    <body>
        <form>
            <input type="text" id="origin_pc" />
            <input type="text" id="dest_pc" />
            <input type="submit" onclick="calculateDistance();">
        </form>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript" src="distance.js"></script>
    </body>
</html>

我对生成的 URL 进行了控制台操作,当打开它时,它给出了正确的 JSON 对象。

【问题讨论】:

    标签: javascript json jquery google-maps-api-3


    【解决方案1】:

    FIDDLE返回 786

    $.getJSON(getData(), function(json) {
       my_json = json;
       $('body').text(my_json.routes[0].legs[0].duration.value);
    });
    

    你需要在getJSON回调函数中使用my_json

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 2021-12-02
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2020-04-22
      相关资源
      最近更新 更多