我正在开发一个项目,您可以根据您输入的州缩写向国家公园 API 询问公园信息,例如 OR(俄勒冈)或 WA(华盛顿)等。我知道如何编写它一个值,使用模板文字,但如果我一次搜索多个状态,那么编写代码时就会变得很棘手。我希望它能像这样向 api 发送调用: https://developer.nps.gov/api/v1/parks?stateCode=or%2Cwa
我会将“or,wa”放入搜索框中
(我正在使用的国家公园 API 端点的文档: https://www.nps.gov/subjects/developer/api-documentation.htm#/parks/getPark )
JS:
'use strict'
$(watchForm());
function watchForm(){
$('form').submit(event => {
event.preventDefault();
getParkInfo();
})
}
function getParkInfo(){
var searchBox = $('.inputBox').val();
var numResults = $('.numPerPage').val();
const url = *** How do I write this???***
fetch(url)
.then(response => response.json())
.then(response => {
console.log(response)
displayResults(response);
})
}
function displayResults(response){
$('#results-list').empty();
for(let i = 0; i < response.data.length; i++){
$('#results-list').append(
`<li>
<a href="${response.data[i].url}"><h3>${response.data[i].fullName}</h3></a>
<p>${response.data[i].description}</p>
<p>${response.data[i].addresses[i]}</p>
<a href="${response.data[i].directionsUrl}"<p>Address</p></a>
</li>`
)
}
$('#results').removeClass('hidden');
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Search Your Favorite National Parks</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>NPS Search Up</h1>
<form>
<input class="inputBox" type="text" required> Search for Park
<br><br>
<input class="numPerPage" type="text" value="10" required> Results per page
<br><br>
<input class="submitBox" type="submit">
</form>
<section id="results" class="hidden">
<h2>Search Results</h2>
<ul id="results-list">
</ul>
</section>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script src="script.js" async defer></script>
</body>
</html>
最佳答案
使用您的基本网址创建一个新的 URL
实例。
var url = new URL("https://developer.nps.gov/api/v1/parks");
然后将查询参数添加到此 URL
实例,如下所示
url.searchParams.append('stateCode', searchBox)
url.searchParams.append('limit', numResults);
关于javascript - 如何将提交文本框中的值连接到 url API 调用中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59588267/