我试图在一个简单的ContextualWeb页面嵌入HTML。按下一个按钮后,新闻API应该返回一个结果列表。我想将响应打印到控制台。
请求看起来是这样的:(但它们没有提供一个完整的HTML示例)
const url ="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?autoCorrect=false&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false"
const options = {
method: 'GET',
headers: {
"X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
"X-RapidAPI-Key": "XXXXXXXX"
},
}
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))快速接口密钥可在此处获取:https://rapidapi.com/contextualwebsearch/api/web-search
希望有一个带有按钮的HTML,并将结果输出到控制台或文本框中。
发布于 2019-04-24 18:44:40
我能够弄明白这一点。下面是一个简单的ContextualWeb页面中嵌入的HTML请求。按下该按钮后,生成的JSON将写入控制台。
<!doctype html>
<html>
<head>
</head>
<body>
<div style="margin: 40px 40px; width: 450px;">
<button onclick="makeGETRequest()">Make the News API call</button>
<p>see console the for results</p>
</div>
<script>
function makeGETRequest() {
const url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?autoCorrect=false&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false"
const options = {
method: 'GET',
headers: {
"X-RapidAPI-Host": "contextualwebsearch-websearch v1.p.rapidapi.com",
"X-RapidAPI-Key": "XXXXXXXXXXXXXXX"
},
}
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
}
</script>
</body>
</html>发布于 2019-04-23 20:33:46
您可以尝试如下所示:
fetch(url, options)
.then(response => response.json())
.then(data => showResults(data))
.catch(e => console.error(e))
showResults(data) {
data.map(news => console.log(news.title));
}在fetch中调用一个处理结果的函数。如果您使用的是纯JavaScript,您可以尝试使用innerHTML来编写结果。
https://stackoverflow.com/questions/55810018
复制相似问题