【问题标题】:Whats the easiest way to create a weather-forecast?创建天气预报最简单的方法是什么?
【发布时间】:2012-01-03 13:31:27
【问题描述】:

我正在开发一个网络应用程序。在这里,我在 JavaScript 中创建了一个弹出窗口。现在我想在这个窗口内创建一个天气预报。

最简单的方法是什么?

我在这里做的:Get weather from Yahoo with jQuery

$(".popup-button").click(function(evt){
//prevent default link behavior
    evt.preventDefault();

//get id from clicked element
var id = $(this).attr("id");

switch (id) {
    case "popup-button-wetter":
        //centering with css
        centerPopup($("#popup-wrapper-wetter"));
        //load popup  
        loadPopupadditional($("#popup-wrapper-wetter"));
        //get weather
        getWeather ()
        break;
          ......


function getWeather () {
     $.get("http://weather.yahooapis.com/forecastrss?w=782458&u=c", function(data){
                   console.log("Data Loaded: " + data);
                 });
            }
    });

但后来我得到了这个错误:

XMLHttpRequest 无法加载 http://weather.yahooapis.com/forecastrss?w=782458&u=c。 Access-Control-Allow-Origin 不允许使用原始文件://。

什么意思?

【问题讨论】:

    标签: javascript xmlhttprequest weather weather-api


    【解决方案1】:

    我知道我迟到了,但我在构建天气页面时遇到了同样的问题。 我使用了 Google 的 API,但你应该可以很容易地为 Yahoo 的 API 重写它:

    在 PHP 文件中做这样的事情:

    <?php
    $lat = explode(".", $_GET["lat"] * 1000000); //latitude returned by JS geolocation
    $lon = explode(".", $_GET["lon"] * 1000000); //longitude returned by JS geolocation
    $api = simplexml_load_string(utf8_encode(file_get_contents("http://www.google.com/ig/api?weather=,,," . $lat[0] . "," . $lon[0] . "&zoom=10&hl=de")));
    echo $api->weather->current_conditions->temp_c->attributes()->data; //prints the current temperature in °C
    ?>
    

    然后通过插入将 HTML 页面的字符集设置为 UTF-8

    <meta charset="utf-8">
    

    进入&lt;head&gt; 标签,以便正确显示ä、ö 和ü 等变音符号。

    Tl;dr:您可以绕过跨域 AJAX 块,方法是通过 PHP 获取 XML 文件,然后将 XMLHttpRequest 发送到本地 PHP 文件。 ;)

    【讨论】:

      【解决方案2】:

      您不能使用 javascript 进行跨域 ajax 请求。

      【讨论】:

        猜你喜欢
        • 2011-04-01
        • 2021-12-24
        • 2014-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        • 2017-04-05
        • 1970-01-01
        相关资源
        最近更新 更多