【问题标题】:Writing JSON in HTML用 HTML 编写 JSON
【发布时间】:2012-05-31 06:30:49
【问题描述】:

我对实际使用 API、获取 JSON 数据并将其放入实际的 HTML 文件并使结果看起来很漂亮是全新的。

我擅长 HTML/CSS/jQuery。但似乎 jQuery 没有这么深入(我可以做基础)

这是我从 Weather Underground 的 API 返回的 JSON 数据示例

    "current_observation": {
    "image": {
    "url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
    "title":"Weather Underground",
    "link":"http://www.wunderground.com"
    },
    "display_location": {
    "full":"Bowling Green, KY",
    "city":"Bowling Green",
    "state":"KY",
    "state_name":"Kentucky",
    "country":"US",
    "country_iso3166":"US",
    "zip":"42101",
    "latitude":"37.02899933",
    "longitude":"-86.46366119",
    "elevation":"154.00000000"
    }

我可以从中看出display_locationcurrent_observation 的内部。

我想将full 拉出并在我的网站上显示为 h1(我实际上想了解更多信息,但我觉得在我完成此操作后我可以处理其余的事情。)

这就是我目前拥有的:

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    </head>
    <body>
        <section id="area"></section>
    </body>
    <script type="text/javascript">
        $().ready(function(){ 
            $.getJSON("http://api.wunderground.com/api/[MY API KEY]/conditions/q/autoip.json",
            function(data){
                $.each(data){
                    content = '<h1>' + json.current_observation.display_location.full + '</h1>';
                    $(content).appendTo("#area");
                 });
              });
           });
    </script>
</html>

它不起作用:-/

任何帮助都很棒。

【问题讨论】:

    标签: jquery json api weather


    【解决方案1】:

    看看这个:

    content = '<h1>' + json.current_observation.display_location.full + '</h1>';
    

    json 指的是什么? $.each(data){ 也是无效的语法。见docs。你的each 循环应该看起来像

    $.each(data, function(i, json) {
        content = '<h1>' + json.current_observation.display_location.full + '</h1>';
        $(content).appendTo("#area");
    });
    

    如果返回的data 是一个对象数组,就像问题中包含的那样,这将起作用。你应该console.log(data) 看到它的形式.. 你可以消除each 循环并使用

    content = '<h1>' + data.current_observation.display_location.full + '</h1>';
    

    【讨论】:

    • 谢谢。我在 URL 的末尾也遗漏了一些东西,但这有帮助。谢谢吨!尝试投票但没有足够高的代表。
    • @Clay_Cauley 很高兴为您提供帮助,只要有机会就 +1
    【解决方案2】:

    这似乎是一个无用的括号。试试看:

    $().ready(function(){ 
            $.getJSON("http://api.wunderground.com/api/[MY API KEY]/conditions/q/autoip.json",
            function(data){
                $.each(data){
                    content = '<h1>' + json.current_observation.display_location.full + '</h1>';
                    $(content).appendTo("#area");
                 } // Change here
              });
           });
    

    【讨论】:

    • 这是不正确的。这将导致Uncaught SyntaxError: Unexpected token {
    • 你是对的。 ); 是正确的,它缺少 function(i, json) 作为第二个参数。对此感到抱歉。
    猜你喜欢
    • 2014-04-28
    • 2018-01-01
    • 1970-01-01
    • 2015-03-17
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多