[英]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.