javascript - 仅显示 [object object],不使用子路径显示来自 api 端点的数据
问题描述
我正在使用 API 来绘制数据 var city = window.location.pathname; var url = '//apiurl';
var infoCity = document.getElementById("info")
fetch(url).then(response => {
return response.json();
}).then(data => {
data.innerHTML += data;
console.log(data);
}).catch(err => {
console.log("there is an error")
});
这让我得到了数据,但它没有在我的 html 文件中显示数据,我在其中有一个 id 为“info”的 div。
相反,它只是说 [Object Object],这是我的第一个问题。
其次,如果用户键入 mysite.com/key,我想根据该键显示数据
我有一个 HTTP 服务器设置,但是当我输入 localhost.com/8080/key 时它不起作用。
但是,对响应进行硬编码,例如
var url = '//apiurl/specifickey' gets the data.
解决方案
info 变量的上下文需要更改。
var city = window.location.pathname;
console.log(city);
var url = '//restcountries.eu/rest/v2/capital' + city;
const info = document.querySelector("#info");
fetch(url).then(response => {
return response.json();
}).then(data => {
info.innerHTML = data;
console.log(data);
}).catch(err => {
console.log("there is an error")
});
推荐阅读
- java - 无法使用文件中的类路径和 cli 上的 @ 使用来运行 java 程序
- sql - 如何查找两个不同日期字段SQL在一定时间间隔内是否匹配?
- java - 容器中的 JVM 错误地计算处理器?
- reactjs - React,为什么在重定向开始之前,我的私有路由会在短时间内呈现给未经授权的用户?
- c - 读取操作中字符设备驱动程序的偏移量
- typo3-9.x - TYPO3 9 在打字稿中获取查询参数
- php - 使用 PHP 从 PHP 文件中仅获取 HTML 代码?
- amazon-web-services - Redshift 表和视图 DDL 生成
- c# - 在 C# 中从特定格式的字符串动态构造 JSON 有效负载
- java - 如何获取当前网页元素的定位器?