簡體   English   中英

從用戶輸入中獲取數據

[英]fetch data from user input

所以我希望用戶在#dateUsetInput 中輸入一個日期,然后在他們單擊按鈕后,我希望獲取 function 獲取該輸入並使用它從該日期獲取適當的圖像。 但是當我這樣做時,會出現此錯誤:

VM113:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
    at getimages (index.js:16:29)
getimages @ index.js:16
await in getimages (async)
(anonymous) @ index.js:12

這是 javascript 代碼:

/*
i want user to input a date
if the date isnt valid put message 'message not valid';
get the date and put it into the fetch function
after that put the image on the screen along with the name of the rover
*/


const button = document.getElementById('updatePic')
button.addEventListener('onclick', getimages())

async function getimages(){
const response = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=${document.getElementById("dateUserInput").value}&api_key=rwX3pO8mONvdxngtstqSuNfwhrwMoGTy6clxqSnu`)
const data = await response.json()
}

這是 html 代碼:

<!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">
    <title>Document</title>
<link href="styles.css" rel="stylesheet">
<script src="index.js" defer></script>

</head>
<body>
    <input type="text" id="dateUserInput">
    <button type="button" id="updatePic">Update Picture</button>
<div class="roverImage"></div>
    
</body>
</html>

出了什么問題,我該怎么辦?

您在第一次加載頁面時使用空輸入值調用 API,而不是在用戶單擊按鈕時。

addEventListener的第一個參數是事件名稱。 onclick不是事件,它是對應於click事件的 HTML 屬性名稱。

第二個參數必須是 function。 您正在調用 function,而不是傳遞對 function 的引用。

const button = document.getElementById('updatePic')
button.addEventListener('click', getimages)

async function getimages() {
  const response = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=${document.getElementById("dateUserInput").value}&api_key=rwX3pO8mONvdxngtstqSuNfwhrwMoGTy6clxqSnu`)
  const data = await response.json()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM