2016-11-18 95 views
1

我试图运行下面的代码:麻烦一些openweathermap API示例代码

var mainWeather = { 
    init: function() { 
    $("#submitWeather").click(function() { 
     return mainWeather.getWeather(); 
    }); 
    }, 

    getWeather: function() { 
    $.get('http://api.openweathermap.org/data/2.5/weather?q=' + $("#cityInput").val() + "," + $("#countryInput").val() + "&APPID=myweatherkey_removed", function(data) { 
     var json = { 
     json: JSON.stringify(data), 
     delay: 1 
     }; 
     echo(json); 
    }); 
    }, 

    // Prints result from the weatherapi, receiving as param an object 
    createWeatherWidg: function(data) { 
    return "<div class='pressure'> <p>Temperature: " + (data.main.temp - 273.15).toFixed(2) + " C</p></div>" + 
     "<div class='description'> <p>Title: " + data.weather[0].main + "</p></div>" + 
     "<div class='description'> <p>Description: " + data.weather[0].description + "</p></div>" + 
     "<div class='wind'> <p>Wind Speed: " + data.wind.speed + "</p></div>" + 
     "<div class='humidity'> <p>Humidity: " + data.main.humidity + "%</p></div>" + 
     "<div class='pressure'> <p>Pressure: " + data.main.pressure + " hpa</p></div>"; 
    } 
    }; 

    var echo = function(dataPass) { 
    $.ajax({ 
    type: "POST", 
    url: "/echo/json/", 
    data: dataPass, 
    cache: false, 
    success: function(json) { 
     var wrapper = $("#weatherWrapper"); 
     wrapper.empty(); 
     wrapper.append("<div class='city'> <p>Place: " + json.name + ", " + json.sys.country + "</p></div>"); 
     wrapper.append(mainWeather.createWeatherWidg(json)); 
    } 
    }); 
}; 

mainWeather.init(); 

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Open Weather API</title> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    </head> 
    <body> 
     <div id="userArea" class="container"> 
      <div id="stateWrapper"> 
       <input type="text" id="cityInput" placeholder="Enter a State" /> 
      </div> 
      <br/> 
      <div id="countryWrapper"> 
       <input type="text" id="countryInput" placeholder="Enter a Country" /> 
      </div> 
      <br/> 
      <div id="buttonArea"> 
       <input type="submit" id="submitWeather" class="btn btn-primary"/> 
       <br/> 
      </div> 
      <!- USED TO SHOW RESULT --> 
      <div id="weatherWrapper"> 
      </div> 
     </div> 
     <script type="text/javascript" src="jquery-3.1.1.slim.js"></script> 
     <script type="text/javascript" src="mainWeather.js"></script> 
    </body> 
</html> 

,但它只是不会做任何事情,当我点击提交。

Chrome调试器首先声明$ .get不是第9行中的函数,因此在搜索后,我将其更改为jquery.get。现在它说这不是一个功能。我不知道我在做什么。有人可以弄清楚这一点吗?

回答

0

jQuery的细长版本排除了Ajax。你可以阅读更多here
只需更换普通版本就可以了。

+0

感谢您的回复。然而,使用正常的jquery运行它现在产生了这个错误:XMLHttpRequest无法加载file:/// C:/ echo/json /。协议方案仅支持交叉源请求:http,data,chrome,chrome-extension,https,chrome-extension-resource。 –

+0

您正在使用文件协议而不是http协议。使用本地服务器,它会工作。搜索并安装XAMPP或WampServer。如果您阅读错误:交叉源请求仅支持协议方案:http ... –

+0

我不认为您拥有所有代码。 – hamza765