HTML中的Javascript在本地工作,但在部署到服务器时不工作

时间:2017-01-23 16:44:30

标签: javascript html server

我一直在构建一个网络应用程序,昨天我尝试添加一些天气数据。我构建了这个简短的HTML文档,它在浏览器中查看时效果很好。但是,今天我部署到Zeit和Firebase Hosting,但是Javascript无法执行,也没有发生任何事情。正如您在此处所见(http://imgur.com/a/TFnEi),没有任何错误。我该如何解决这个问题?

<!DOCTYPE html>
<html>

<head>
  <title>Display Weather</title>
</head>

<body>
  <style>
  h1{
     font-family: Arial;
     margin:auto;
     }
  p{
     font-family: Arial;
     margin:auto;
     }
     img{
        border: 2px solid blue;
        border-radius: 10px;
        }
  </style>
  <h1> Current weather in Berlin: </h1>
  <p id="forecast_metric">Gathering data...</p>
  <p id="temp_c">Gathering data...</p>
  <p id="WIP">No data</p>
  <p id="weathercond">Gathering data...</p>
  <p id="visibility">Gathering data...</p>
  <p id="updated">Gathering data...</p>
  <img id="weathericon" src="test.png">
  <script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', "http://api.wunderground.com/api/APIKEY/conditions/forecast/q/Germany/Berlin.json", true);
  xhr.send();

  xhr.onreadystatechange = processRequest;

   function processRequest(e) {
   if (xhr.readyState == 4 && xhr.status == 200) {
         var response = JSON.parse(xhr.responseText);

         var temp_c = response.current_observation.temp_c
         var weathercond = response.current_observation.weather
         var weathericon = response.current_observation.icon_url
         var updated = response.current_observation.observation_time
         var visibilitykm = response.current_observation.visibility_km

         alert('The temperature is ' + temp_c + ' degrees Celsius in Berlin right now. The Forecast for ' + response.forecast.txt_forecast.forecastday[1].title + ' is : ' + response.forecast.txt_forecast.forecastday[1].fcttext_metric);
         document.getElementById("forecast_metric").innerHTML =  "The current forecast for today is: " + response.forecast.txt_forecast.forecastday[1].fcttext_metric
         document.getElementById("temp_c").innerHTML =  "Temperature: " + temp_c + " degrees Celsius"
         document.getElementById("weathercond").innerHTML =  "Weather: " + weathercond
         document.getElementById("visibility").innerHTML =  "Visibility: " + visibilitykm + " km"
         document.getElementById("updated").innerHTML =  updated
         document.getElementById("weathericon").src = weathericon;
    }

  }

  </script>

</body>

</html>

编辑: 我发现了问题 - 浏览器不接受HTTP而是需要HTTPS。谢谢你的答案!

1 个答案:

答案 0 :(得分:-2)

这只是一个猜测 - 但也许你是APIKEY从域名无效?

enter image description here

在Chrome中打开DEV控制台,它可能会对您有所帮助!

请参阅http://api.wunderground.com/api/APIKEY

当我用不正确的APIKEY打开它时,我会收到:

{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  }
        ,
    "error": {
        "type": "keynotfound"
        ,"description": "this key does not exist"
    }
    }
}

要查看这是否是您的问题,请打开DEV控制台,单击XHR选项卡,如果您收到与上述相同或类似的响应,则您的APIKEY无效。

我希望这有帮助!

相关问题