【问题标题】:Can't extract data with getJSON无法使用 getJSON 提取数据
【发布时间】:2017-03-22 01:51:51
【问题描述】:

我现在正在学习 freecampcode 课程,我在当地的天气应用程序中。

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

我还尝试在 .getJSON 函数上使用直接 api 链接,但即便如此,我还是从 json 获得 0 输入,我使用 console.log(data) 和 $("#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>

【问题讨论】:

    标签: javascript jquery json


    【解决方案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 应该是一个绝对URL,即。它需要一个 http:// 或 https:// 前缀。

    【讨论】:

    • 我尝试了您的解决方案,但在 Firefox 控制台上没有得到任何输出。
    • 检查控制台中的请求以确保它按预期工作。如果您遇到错误,请告诉我
    • 感谢您的快速回答,我收到以下错误:“Header CORS "Access-Control-Allow-Origin" missing”
    • 好的,这意味着 openweathermap API 不会在响应中返回 CORS 标头。不幸的是,这意味着你不能从 JS 调用他们的 API。您将不得不使用服务器端代码。你所拥有的将不起作用。
    【解决方案2】:

    函数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的错误拼写。

    【讨论】:

    • 我尝试了您的解决方案,但在 Firefox 控制台上没有得到任何输出。
    • 我使用的是 Firefox,它对我有用,尽管我必须使用不同的 JSON 服务器进行测试(我没有你的 API id)。我在您的问题中注意到您在返回语句中拼错了apiLink(不应该都是小写)。除此之外,我认为它没有理由不工作。
    【解决方案3】:

    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 设为全局变量来解决,但这不是解决问题的好方法

    【讨论】:

    • OP 正在调用 getCordinates(),它不会返回任何内容 - 并且不能因为 getCurrentPosition() 调用是异步的
    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多