$ .getJSON(url.params)是否正确格式化了URL?

时间:2016-03-25 12:46:23

标签: javascript json

我正在从OpenWeatherAPI访问JSON数据。 URL的正确格式为

http://api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=34lkj349gga9s8dug9sd8hg

哪里?q = {city}& APPID = {API_key}

假设我提供了url,q param和APPID参数。我使用$ .getJSON功能来检索JSON数据。 $ .getJSON是否知道URL格式为?,=和&或者我是否必须用自己的参数编写这些内容?目前我返回的是localhost /?

这是我写的短节目。我很好地评论了我希望它如何发挥作用。

  // Here is how the final url should look:
  // api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=33lkr3jlfj39asdflk

var weatherSearch = '';
  // weather-search is my html form id. On submit, send the input
  // (which is city name) to the function getWeather.
$('#weather-search').submit(function(event) {
weatherSearch = $('#weatherQuery').val();
event.preventDefault();
getWeather(weatherSearch);
});

  // getWeather has params q (city name), and APPID (API key).
function getWeather(weatherSearch) {
var params = {
        q: weatherSearch,
        APPID: '33lkr3jlfj39asdflk'
};
  // This is the url that goes before the params.
url = 'http://api.openweathermap.org/data/2.5/weather/';
  // Request data using url and params above.
  // Does $.getJSON format the url properly?
$.getJSON(url. params, function(data) {
  // Pass JSON data to showWeather function.
        showWeather(data.items);
        console.log(data.items);
});
}

function showWeather(weather) {
  // Show JSON data (weather) in html div id="weatherResults"
$('#weatherResults').html(weather);

}

这是JavaScript引用的html。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>weather</title>
<script src="/jquery.js"></script>
<script src="openweather.js"></script>
</head>
<body>

<form id="weather-search">
<input type="text" id="weatherQuery"></input>
<input type="submit" value="Submit"></input>
</form>

<div id="weatherResults">
</div>

2 个答案:

答案 0 :(得分:1)

尝试使用逗号&#34; ,&#34; dot&#34; .&#34; :

$.getJSON(url, params, function(data) {
  // Pass JSON data to showWeather function.
        showWeather(data.items);
        console.log(data.items);
});

答案 1 :(得分:0)

是的,它会自动使用?q = weatherSearch&amp; APPID = 33lkr3jlfj39asdflk

对网址进行编码

只需将你的getJson切换到

即可
$.getJSON(url, params, function(data) {
  // Pass JSON data to showWeather function.
        showWeather(data.items);
        console.log(data.items);
});

url

之后您有一个期间而不是逗号

使用一个工作示例查看此codepen http://codepen.io/anon/pen/jqwPyQ