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

Does $.getJSON(url.params) correctly format a URL?

本文关键字:url 格式化 是否 params getJSON      更新时间:2023-09-26

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

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

在哪里?q={城市}&APPID={API_key}

假设我提供url、q参数和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>

尝试点"."的逗号","instad:

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

是的,它会自动用?q=天气搜索&APPID=33lkr3jlfj39asdflk

只需将您的getJson切换到

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

url 后有一个句点而不是逗号

请参阅此代码笔和一个工作示例http://codepen.io/anon/pen/jqwPyQ