简体   繁体   English

如何使用用户输入 function 从 API 获取数据

[英]How to fetch data from API with user input function

I'm new to APIs.我是 API 新手。 I want to make a flight search API and I have a validation function and then I want to fetch the data based on the user input (which are still airport codes instead of city names).我想进行航班搜索 API 并且我有一个验证 function 然后我想根据用户输入(仍然是机场代码而不是城市名称)获取数据。 But when I console.log the fetchFlights like this: fetchFlights(AAR, BAJ, economy then I get an error saying that AAR is not defined, but the API works on airport codes. I have tried several ways to solve this but nothing so far did the job. i also tried:; fetchFlights(depAirport, arrAirport, travelClass) and that is in the code and that gave the same error.但是当我这样控制台记录 fetchFlights 时:完成了这项工作我也试过:; fetchFlights(depAirport, arrAirport, travelClass) 这在代码中并且给出了同样的错误。

When I do this: fetchFlights("AAR", "BAJ", "Economy") I get: GET https://google-flights-search.p.rapidapi.com/search?departure_airport_code=AAR%22&arrival_airport_code=BAJ&flight_class=Economy 500 (Internal Server Error)当我这样做时: fetchFlights("AAR", "BAJ", "Economy") 我得到: GET https://google-flights-search.p.rapidapi.com/search?departure_airport_code=AAR%22&arrival_airport_code=BAJ&flight_class=Economy 500内部服务器错误)

Does anyone know how I could get the data?有谁知道我如何获取数据? Thanks a lot in advance!提前非常感谢!

 function validateForm() { let depAirp = document.getElementById("field").value; let arrAirp = document.getElementById("field2").value; let travelCl = document.getElementById("field3").value; if (depAirp.value == null || data == '' || arrAirp.value == null || data == '' || travelCl.value == null || data == '') { document.getElementById("errorMessage2").innerHTML = "Please fill all the fields"; } else { return 'true'; } } function fetchFlights(depAirport, arrAirport, travelClass) { validateForm() fetch(`https://google-flights-search.p.rapidapi.com/search?departure_airport_code=${depAirport}"&arrival_airport_code=${arrAirport}&flight_class=${travelClass}`, { "method": "GET", "headers": { "x-rapidapi-host": "google-flights-search.p.rapidapi.com", "x-rapidapi-key": "283ff4e872msh5329c2c6fdca6d0p1655aejsnbaa6f9870616" } }).then(response => response.json()).then(json => { console.log(json.flights); }) }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <link rel="stylesheet" href="style:css" /> <title>Flight Explorer</title> </head> <body> <div class="section"> <img class="logo" src="https.//static.thenounproject.com/png/3782905-200.png" alt="" /> </div> <form id="form" onsubmit="validateForm()"> <p class="title-action">Depart from</p> <input value="" id="field" type="text" placeholder="" autocomplete="off" /> <p class="title-action">Destination</p> <input id="field2" type="text" placeholder="" autocomplete="off" /> <p>Departing Date</p> <input id="field3" type="text" placeholder="" autocomplete="off" /> <small id="errorMessage2">s</small> <button class="submitSearch" type="submit">Find flights</button> </form> </div> </div> <div id="results"> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> </div> <div id="final-results"></div> </body> </html>

  • You are passing parameters where you should not and vice versa您正在传递不应传递的参数,反之亦然
  • You also get values and test the value.value您还可以获取值并测试 value.value
  • Also you tested data which does not exist您还测试了不存在的data
  • There was a " in the URL that does not belong there URL 中有一个"不属于那里”
  • Lastly I change date to travel class in the form You need to add the date back somehow I think, but that is described in their API最后,我将日期更改为旅行 class 的形式你需要以某种方式添加日期,但在他们的 API 中有描述
  • I get invalid API key but the code will work much better than yours我得到无效的 API 密钥,但代码会比你的代码好得多

This is likely what you MEANT to do这可能是你想要做的

 function fetchFlights(depAirport, arrAirport, travelClass) { fetch(`https://google-flights-search.p.rapidapi.com/search?departure_airport_code=${depAirport}&arrival_airport_code=${arrAirport}&flight_class=${travelClass}`, { "method": "GET", "headers": { "x-rapidapi-host": "google-flights-search.p.rapidapi.com", "x-rapidapi-key": "283ff4e872msh5329c2c6fdca6d0p1655aejsnbaa6f9870616" } }).then(response => response.json()).then(json => { console.log(json.flights); }) } window.addEventListener("load", function() { // when page loads and page elements are available document.getElementById("form").addEventListener("submit", function(e) { e.preventDefault(); // stop submission let depAirp = document.getElementById("field").value; let arrAirp = document.getElementById("field2").value; let travelCl = document.getElementById("field3").value; if (depAirp == "" || arrAirp == "" || travelCl == "") { document.getElementById("errorMessage2").innerHTML = "Please fill all the fields"; } else { fetchFlights(depAirp, arrAirp, travelCl) } }) })
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <link rel="stylesheet" href="style:css" /> <title>Flight Explorer</title> </head> <body> <div class="section"> <img class="logo" src="https.//static.thenounproject.com/png/3782905-200.png" alt="" /> </div> <form id="form"> <p class="title-action">Depart from</p> <input value="" id="field" type="text" placeholder="" autocomplete="off" /> <p class="title-action">Destination</p> <input id="field2" type="text" placeholder="" autocomplete="off" /> <p>Travel class</p> <input id="field3" type="text" placeholder="" autocomplete="off" /> <small id="errorMessage2"></small> <button class="submitSearch" type="submit">Find flights</button> </form> </div> </div> <div id="results"> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> </div> <div id="final-results"></div> </body> </html>

The error from when you try to run the code in the Console is because you're passing variable names into the function in places of values, but those variables don't exist, so JS cannot use them to pass in a real value.当您尝试在控制台中运行代码时出现的错误是因为您将变量名称传递给 function 以代替值,但是这些变量不存在,因此 JS 不能使用它们来传递实际值。 It looks like you didn't realise that literal strings need to have quote marks around then.看起来您当时没有意识到文字字符串需要有引号。 Running跑步

fetchFlights('AAR', 'BAJ', 'economy')

resolves that particular problem.解决了该特定问题。


Meanwhile, there are a few issues with the actual form itself:同时,实际表单本身存在一些问题:

  1. Your code never actually calls the fetchFlights function, even when the validation passed即使验证通过,您的代码也不会真正调用 fetchFlights function
  2. You don't prevent the form from doing a default postback, so the fetch code can never run您不会阻止表单执行默认回发,因此提取代码永远不会运行
  3. There's a typo in the API URL template (a stray " which doesn't belong) API URL 模板中有一个错字(一个不属于的流浪"
  4. It's recommended to use unobtrusive event handler syntax using addEventListener rather than inline event handlers within the HTML markup.建议在 HTML 标记中使用使用addEventListener的不显眼的事件处理程序语法,而不是内联事件处理程序。
  5. You don't actually need your custom validation code because you can just set required attributes on all the input fields您实际上不需要自定义验证代码,因为您只需在所有输入字段上设置required的属性
  6. Your Date field doesn't match the "Travel Class" value you're sending to the API.您的日期字段与您发送到 API 的“旅行等级”值不匹配。 I changed the wording of the label on the form.我更改了表格上 label 的措辞。

This version fixes those issues:此版本修复了这些问题:

 var frm = document.querySelector("#form"); form.addEventListener("submit", function(event) { event.preventDefault(); //prevent a normal submit, to allow JS code to run fetchFlights(); }); function fetchFlights(depAirport, arrAirport, travelClass) { let depAirp = document.querySelector("#field").value; let arrAirp = document.querySelector("#field2").value; let travelCl = document.querySelector("#field3").value; fetch(`https://google-flights-search.p.rapidapi.com/search?departure_airport_code=${depAirport}&arrival_airport_code=${arrAirport}&flight_class=${travelClass}`, { "method": "GET", "headers": { "x-rapidapi-host": "google-flights-search.p.rapidapi.com", "x-rapidapi-key": "283ff4e872msh5329c2c6fdca6d0p1655aejsnbaa6f9870616" } }).then(response => response.json()).then(data => { console.log(JSON.stringify(data)); }); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <link rel="stylesheet" href="style:css" /> <title>Flight Explorer</title> </head> <body> <div class="section"> <img class="logo" src="https.//static.thenounproject.com/png/3782905-200.png" alt="" /> </div> <form id="form"> <p class="title-action">Depart from</p> <input value="" id="field" type="text" placeholder="" autocomplete="off" required /> <p class="title-action">Destination</p> <input id="field2" type="text" placeholder="" autocomplete="off" required /> <p>Travel Class</p> <input id="field3" type="text" placeholder="" autocomplete="off" required/> <button class="submitSearch" type="submit">Find flights</button> </form> </div> </div> <div id="results"> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> <div class="col"> </div> </div> <div id="final-results"></div> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM