无法使用getJSON提取数据

时间:2016-11-08 12:23:27

标签: javascript jquery json

我正在做freecampcode课程,现在我在当地的weatherapp。

我的问题是每次我尝试使用,我得到apiLink没有定义。我知道.getJSON部分无法与definedCordinates函数中定义的var连接。

此外,我尝试在.getJSON函数上使用直接api链接,但即使我从json获得0输入,我使用console.log(数据)和$(“#temp”)。text来检查来自json的输入。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>My Local Weather App</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="custom.css">.
    <script type="text/javascript">
    $(document).ready(function(){
        getCordinates();
        $.getJSON(apiLink, function(data){
            console.log(data);
        })
    })

    function getCordinates(){
        navigator.geolocation.getCurrentPosition(definedCordinates);
    }

    function definedCordinates(position){
        var latitude = Math.floor(position.coords.latitude);
        var longitude = Math.floor(position.coords.longitude);
        var apiLink = "api.openweathermap.org/data/2.5/weather?lat=" + latitude +"&lon="+ longitude +"&APPID=##########";
        return apilink;
}
    </script>


<body>
    <div class="container-fluid">
        <div class="row" id="titleRow">
            <div class="col-md-4 col-md-offset-4">
                <h1>My Local Weather App</h1>
            </div>
        </div>
        <div class="row" id="locationRow">
            <div class="col-md-4 col-md-offset-4">
                <div class=row">
                    <div class="col-md-6" style="background-color: grey">
                        <p style="text-align:center">icon</p>
                    </div>
                    <div class="col-md-6" style="background-color: yellow">
                        <p style="text-align:center" id="temp">temp</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="row" id="dataRow">
            <div class="col-md-6 col-md-offset-3">
                <div class="row">
                    <div class="col-md-4" style="background-color: grey">
                        <p id="name"> city name</p>
                    </div>
                    <div class="col-md-4" style="background-color: yellow">
                        <p> sky</p>
                    </div>
                    <div class="col-md-4" style="background-color: grey">
                        <p> wind</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="row" id="poweredBy">
            <div class="col-md-6 col-md-offset-3">
                <div class="row">
                    <div class="col-md-6" id="powered">
                        <p> Powered by openweathermap.org API </p>
                    </div>
                    <div class="col-md-6"style="background-color: yellow">
                        <p> button celsius or farh </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

问题是因为apiLink函数中定义了definedCordinates()变量,这远远超出document.ready处理程序的范围。

要解决此问题,您需要重构逻辑,以便通过在异步方法上使用适当的回调来使apiLink可用于AJAX请求。试试这个:

$(document).ready(function(){
    getCordinates(function(apiLink) {
        $.getJSON(apiLink, function(data) {
            console.log(data);
        })
    });
})

function getCordinates(callback) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = Math.floor(position.coords.latitude);
        var longitude = Math.floor(position.coords.longitude);
        var apiLink = "https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=##########"
        callback && callback(apiLink)
    });
}

另请注意,apiLink应为绝对网址,即。它需要http://https://前缀。

答案 1 :(得分:1)

函数getCordinates不返回任何内容,即使它发生了,也无法同步返回URL,因为回调definedCordinates只会稍后异步调用。其次,该回调的返回值(即URL)目前尚未使用,但在遗忘中消失。

有几种方法可以解决这个问题,但在这种情况下,添加一个承诺(对于$.getJSON已经承诺的承诺)似乎是一个很好的解决方案:

$(document).ready(function(){
    getCordinates().then(function(apiLink) {
        // this executes when the promise returned by getCordinates is resolved:
        return $.getJSON(apiLink);
    }).then(function (data) {
        // this executes when the promise returned by getJSON is resolved:
        console.log(data);
    });
})

function getCordinates() {
    // return a promise that resolves when you get the current position:
    return new Promise(function (resolve) {
        navigator.geolocation.getCurrentPosition(function (position) {
            resolve(definedCordinates(position));
        });
    });
}

函数definedCordinates可以保持原样,但在return语句中更正apiLink的错误拼写。

答案 2 :(得分:0)

getCordinates需要返回一个值(你的url),你需要将该值传递给getJSON而不是一个对象(它与你的文档准备好在同一范围内!)

更可能的修复方式如下:

$(document).ready(function(){
    var url = getCordinates();
    $.getJSON(url, function(data){
        console.log(data);
    })
})

function getCordinates(){
    navigator.geolocation.getCurrentPosition(definedCordinates);
}

function definedCordinates(position){
    var latitude = Math.floor(position.coords.latitude);
    var longitude = Math.floor(position.coords.longitude);
    var apiLink = "api.openweathermap.org/data/2.5/weather?lat=" + latitude +"&lon="+ longitude +"&APPID=##########";
    return apilink;
}

您还会遇到一个问题,因为您没有将任何内容传递给definedCoordinates。

这可以通过使apiLink成为全局变量来解决,但这不是解决问题的好方法