В моем поиске, когда я добавляю штаты, такие как Мичиган или Огайо, он возвращает назад Национальные парки, эта часть работает нормально. Моя проблема в том, что когда вы просто добавляете аббревиатуру штата, это не очень хорошо работает.
В документации API я могу добавить 'stateCode Список разделенных запятыми двухсимвольных кодов состояния.' на котором у меня есть. В свою очередь это выдает CURL, с которым я не знаком вообще. Это curl: curl -X GET "https://developer.nps.gov/api/v1/parks?stateCode=AK%2C%20AL%2C%20AR%2C%20AZ%2C%20CA%2C%20CO%2C%20CT%2C%20DC%2C%20DE%2C%20FL%2C%20GA%2C%20HI%2C%20IA%2C%20ID%2C%20IL%2C%20IN%2C%20KS%2C%20KY%2C%20LA%2C%20MA%2C%20MD%2C%20ME%2C%20MI%2C%20MN%2C%20MO%2C%20MS%2C%20MT%2C%20NC%2C%20ND%2C%20NE%2C%20NH%2C%20NJ%2C%20NM%2C%20NV%2C%20NY%2C%20OH%2C%20OK%2C%20OR%2C%20PA%2C%20RI%2C%20SC%2C%20SD%2C%20TN%2C%20TX%2C%20UT%2C%20VA%2C%20VT%2C%20WA%2C%20WI%2C%20WV%2C%20WY&api_key=VBJvAbqe0D9w3pyhaHcw4p4MB2dNgSgxMjvCbyEH" -H" принять: application / json "
Как я могу добавить это в свой javascript, чтобы это работало, когда я просто хочу вставить двухбуквенное сокращение состояния?
"use strict";
const apiKey = "VBJvAbqe0D9w3pyhaHcw4p4MB2dNgSgxMjvCbyEH";
const searchURL = "https://api.nps.gov/api/v1/parks";
function formatQueryParams(params) {
const queryItems = Object.keys(params).map(
key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
);
return queryItems.join("&");
}
function displayResults(responseJson) {
// if there are previous results, remove them
console.log(responseJson);
$("#results-list").empty();
// iterate through the items array
for (let i = 0; i < responseJson.data.length; i++) {
// for each park object in the items
//array, add a list item to the results
//list with the park title, description,
//and thumbnail
$("#results-list").append(
`<li><h3>${responseJson.data[i].fullName}</h3>
<p>${responseJson.data[i].description}</p>
<a href='${responseJson.data[i].url}'>${responseJson.data[i].url}</a>
</li>`
);
}
//display the results section
$("#results").removeClass("hidden");
}
function getNationalParksInfo(query, maxResults = 10) {
const params = {
key: apiKey,
q: query,
limit: maxResults - 1
};
const queryString = formatQueryParams(params);
const url = searchURL + "?" + queryString;
console.log(url);
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson))
.catch(err => {
$("#js-error-message").text(`Something went wrong: ${err.message}`);
});
}
function watchForm() {
$("form").submit(event => {
event.preventDefault();
const searchTerm = $("#js-search-term").val();
const maxResults = $("#js-max-results").val();
getNationalParksInfo(searchTerm, maxResults);
});
}
$(watchForm);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>National Parks by Location</title>
<link rel="stylesheet" href="style.css" />
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"
></script>
</head>
<body>
<div class="container">
<h1>Your National Parks</h1>
<form id="js-form">
<label for="search-term">Search term</label>
<input type="text" name="search-term" id="js-search-term" required />
<label for="max-results">Maximum results to return</label>
<input
type="number"
name="max-results"
id="js-max-results"
value="10"
/>
<input type="submit" value="Go!" />
</form>
<p id="js-error-message" class="error-message"></p>
<section id="results" class="hidden">
<h2>Search results</h2>
<ul id="results-list"></ul>
</section>
</div>
<script src="app.js"></script>
</body>
</html>
Желаемый результат для меня - либо ввести полное название штата для аббревиатуры, и я получу те же результаты поиска.