【问题标题】:getJSON overrides HTML background colorgetJSON 覆盖 HTML 背景颜色
【发布时间】:2016-02-17 15:59:17
【问题描述】:

我正在创建一个使用 jQuery、iFrames 并具有简单 CSS 的 HTML 页面。当我对来自 openweathermap.org 的 json 文件运行 jQuery 脚本时,它会覆盖设置的 HTML 背景颜色以及任何 iframe。有什么建议吗?

<style>
    body {
        background-color: #ff5000;
    }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

<div id = "weather"></div>
<script>
    $( "weather" ).ready(function(){ 
        $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=Castlebar,ie&appid=44db6a862fba0b067b1930da0d769e98");
        document.write('hello');
        console.log('works')
    });

</script>

【问题讨论】:

标签: javascript jquery html json api


【解决方案1】:

JSON RESTful 请求不应改变您的背景...

您的请求需要一个回调函数,以便您可以处理数据。

$('#weather').ready(function(request) {
  $.getJSON('http://api.openweathermap.org/data/2.5/weather', {
    q     : 'Castlebar,ie',
    appid : '44db6a862fba0b067b1930da0d769e98'
  }, function(data, textStatus, jqXHR) {
    var city    = data.name;
    var country = data.sys.country;
    var weather = data.weather[0].description;
    
    // Prints: "Current weather for Castlebar, IE: light rain"
    $('#weather').html('Current weather for ' + city + ', ' + country + ': ' + weather);
  });
});
body {
  background-color: #ff5000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="weather"></div>

JSON 响应

{
  "coord": {
    "lon": -9.3,
    "lat": 53.85
  },
  "weather": [
    {
      "id": 500,
      "main": "Rain",
      "description": "light rain",
      "icon": "10d"
    }
  ],
  "base": "cmc stations",
  "main": {
    "temp": 278.229,
    "pressure": 1016.87,
    "humidity": 100,
    "temp_min": 278.229,
    "temp_max": 278.229,
    "sea_level": 1024.44,
    "grnd_level": 1016.87
  },
  "wind": {
    "speed": 5.27,
    "deg": 231.001
  },
  "rain": {
    "3h": 0.2
  },
  "clouds": {
    "all": 76
  },
  "dt": 1455729355,
  "sys": {
    "message": 0.0024,
    "country": "IE",
    "sunrise": 1455695530,
    "sunset": 1455731463
  },
  "id": 2965654,
  "name": "Castlebar",
  "cod": 200
}

【讨论】:

    【解决方案2】:

    我认为您要做的是更改#weather 的HTML,而不是重写整个文档。你可以这样做:

    $('#weather').html("INSERT YOUR DESIRED CONTENT HERE");
    

    因此,您从 getJSON() 解析 JSON,提取有趣的信息,并使用上述代码行将其插入到 #weather 中。我已经为您准备了一个带有示例代码的 JSFiddle。我不得不在那里对 json 进行硬编码,因为 JSFiddle 不会让我从您的链接中获取 JSON,因为它不是 HTTPS 链接,而只需在您自己的页面上用 var json = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=Castlebar,ie&amp;appid=44db6a862fba0b067b1930da0d769e98"); 替换我的 Fiddle 中的 var json = *JSON*,它应该可以工作.

    https://jsfiddle.net/k87yuats/

    编辑:我忘了在您自己的页面上提及,您必须使用 getJson() 的 .done() 功能来确保在尝试解析 JSON 数据之前完成 AJAX 请求:http://api.jquery.com/jquery.getjson/

    【讨论】:

      猜你喜欢
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多