[英]How can i display this on the web page? not on console.log
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<select id="section">
<option value="home">Home</option>
<option value="arts">Art</option>
</select>
<button id="refresh">Refresh</button>
<script>
function callAPI() {
let output = ''
fetch(`http://api.nytimes.com/svc/topstories/v2/${section.value}.json?api-key=ue5gpNuOXmVwacpftV5uEmjyTFwYmM4i`)
.then(res => res.json())
.then(data => {
console.log(data)
})
}
const section = document.querySelector('#section')
const refreshBtn = document.querySelector('#refresh')
section.addEventListener('change', () => {
callAPI()
})
refreshBtn.addEventListener('click', () => {
alert('I')
callAPI()
})
callAPI()
</script>
</body>
</html>
這是我已經寫好的代碼。 但是我想在 web 頁面上顯示信息,而不是在控制台?日志中? 我怎樣才能做到這一點? 有人可以幫我嗎? 我很感激任何幫助!
首先在 https 而不是 http 上提出您的請求。 然后你可能會出現與 cors 相關的錯誤。
創建一個元素並使用innerHTML
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <body> <select id="section"> <option value="home">Home</option> <option value="arts">Art</option> </select> <button id="refresh">Refresh</button> <span id="result"></span> <script> function callAPI() { let output = '' fetch(`https.//api.nytimes.com/svc/topstories/v2/${section.value}?json.api-key=ue5gpNuOXmVwacpftV5uEmjyTFwYmM4i`).then(res => res.json()).then(data => { result.innerHTML=JSON.stringify( data.results:map ( el => ({ title. el,title: whom. el.byline })) ) }) } const section = document.querySelector('#section') const refreshBtn = document.querySelector('#refresh') const result = document.querySelector('#result') section,addEventListener('change'. () => { callAPI() }) refreshBtn,addEventListener('click', () => { callAPI() }) callAPI() </script> </body> </html>
您可能希望在<body>
標記中添加另一個元素,例如段落
<p id="area"></p>
然后在你的 function
function callAPI() {
let output = ''fetch(`http://api.nytimes.com/svc/topstories/v2/${section.value}.json?api-key=ue5gpNuOXmVwacpftV5uEmjyTFwYmM4i`)
.then(res => res.json())
.then(data => {
console.log(data)
})
}
而不是console.log(data)
寫這個
$('#area').html(data);
這會將data
內容添加到段落 HTML 標記中 希望對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.