【问题标题】:Location aware and weather website. Problems with Javascript and cross site XML位置感知和天气网站。 Javascript 和跨站点 XML 的问题
【发布时间】:2012-04-04 11:28:29
【问题描述】:

尝试创建一个页面,通过 Javascript 向用户显示当前天气。因此,我的代码可以找到用户位置并正确创建一个完全符合 Google 天气 API 约定的 URL,但问题是发出 xml 请求并将天气数据返回给用户证明是一个问题。我已经为 apache 安装了 mod_rewrite 来解决跨站点 xml 问题,但它似乎无法正常工作。其他任何人都知道如何让这个工作?这是我到目前为止的代码:

<html>
<head>
    <meta name="robots" value="none" />
    <title></title>
</head>

<body>

<div id="yourinfo">

</div>
<b>url:</b> <span id="url"></span><br />
<b>city:</b> <span id="city"></span><br />

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
    if(google.loader.ClientLocation)
    {
        visitor_lat = google.loader.ClientLocation.latitude;
        visitor_lon = google.loader.ClientLocation.longitude;
        visitor_city = google.loader.ClientLocation.address.city;
        visitor_region = google.loader.ClientLocation.address.region;
        visitor_country = google.loader.ClientLocation.address.country;
        visitor_countrycode = google.loader.ClientLocation.address.country_code;
        weather_http = 'http://www.google.com/ig/api?weather=' + visitor_city + '+' + visitor_region;

        var Result = weather_http;

    }
    else
    {
        document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
    }


    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET",'weather_http',false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;

    document.getElementById("url").innerHTML=weather_http
    document.getElementById("city").innerHTML=xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;

    </script>

【问题讨论】:

  • 到底是什么问题?什么不起作用?
  • 我很难说,因为我是 javascript 新手,没有简单的方法来测试它。似乎 URL 在 weather_http 变量中返回,但是当我执行 GET 请求并尝试解析它时,没有任何内容被写入屏幕

标签: javascript xml geolocation weather


【解决方案1】:

Wikipedia has a great example 了解如何设置有效的 XMLHttpRequest。

基本上,您需要为您的请求设置一个 onreadystatechange 侦听器,然后通过 URL(即:weather_http,而不是代码中的“weather_http”)打开连接,最后发送所有数据。

因为 XHR 请求是异步的,所以您必须实现该回调,以便 javascript 引擎知道 XHR 响应时要做什么。

当您让 XHR 工作时,您会发现如果没有代理,您将无法做您想做的事情。这是因为 XHR 的跨域策略。您无法通过 XHR 从与应用程序当前域不同的域获取数据。

要克服这个问题,您需要实现一个服务器代理来将 XHR 提交到其他域,检索响应并将其返回给您的应用程序。有大量免费代理可用,只需 search google for it

最后,您将遇到最后一个问题,即告诉您的代理将 ?weather=city 附加到目标 URL。

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多