我有一个表单,用户可以在其中输入纬度和经度(坐标)。 我要做的是基于以下REST API显示信息: https://rest.soilgrids.org/query.html
这就是我创造的。
<p>
Latitude : <input id='lat'/> <br/>
Longitude: <input id='lon'/> <br/>
<button id='submit'>Submit<button/>
<p/>
那么我该如何提取输入并使其显示基于API的可用信息。我是新手,因此需要JS帮助
答案 0 :(得分:0)
您将需要执行Ajax调用以从API获取数据。
假设您的脚本中包含jQuery,则示例为:
// The code will only run on form submit
$("#form").on("submit", (evt) => {
evt.preventDefault();
// Abbreviate on how you get the longitude / latitude
const longitude = ...
const latitude = ...
const url = "https://rest.soilgrids.org/query?lon=" + logitude + "&lat=" + latitude
$.ajax(url, {
method: "GET" // You need to read the documentation of the API provider to see if it is a POST or GET call
// There are more option that you can set. Read the documentation of jquery,
success: (data) => {
// This is where you perform effect after you get the data from API
}
})
})
有关更多详细信息,请参见https://api.jquery.com/jquery.ajax/
修改
刚刚看到了您的代码。应该进行一些小的更改以使其更好:
// Warp it into a <form> block so that it will response to "Enter" Key
<form id="form">
Latitude : <input id='lat'/> <br/>
Longitude: <input id='lon'/> <br/>
// Good habit to state the type of a button
<button type="submit" id='submit'>Submit<button/>
</form>
答案 1 :(得分:0)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style>
</style>
<title>Untitled Document</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-6">
<label>Latitute</label>
<input type="number" class="form-control" id="lat">
</div>
<div class="col-sm-6">
<label>longitute</label>
<input type="number" class="form-control" id="long">
</div>
<div class="col-sm-3">
<input type="button" class="btn btn-primary" id="search" value="get Info">
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#search").click(function(){
let lat = $("#lat").val();
let long = $("#long").val();
if(lat == "" || long==""){
alert("please enter lat and long to get info");
return;
}
else{
$.ajax({
type:"GET",
url:`https://rest.soilgrids.org/query?lon=${long}&lat=${lat}`,
dataType: "json",
success:function(response){
console.log(response);
},
error:function(jqXHR, exception){
console.log("error");
}
})
}
})
})
</script>
</body>
</html>
尝试