注意:我是 JavaScript 和 html 的新手,所以有很多東西我還不太明白。
我正在嘗試制作一個 Web 應用程式,該應用程式使用公共汽車時刻表 API 來顯示我公寓周圍的公共汽車時間。我設法檢索了資料,但我很難在 html 中顯示該資料。(編輯:它可能是一個 SDK,我真的不知道有什么區別)
// this is the function write_bus() in my javascript file departures.js:
function write_bus() {
document.getElementById("bustime-kong").innerHTML = data;
}
// 'data' is a variable in javascript that contains the information I fetched from the client, and is what I am trying to show.It is on the following format:
const data = {
aimedArrivalTime: '2022-01-06T12:36:00 0100',
aimedDepartureTime: '2022-01-06T12:36:00 0100',
cancellation: false,
date: '2022-01-06',
destinationDisplay: {
frontText: 'xxx'
},
expectedDepartureTime: '2022-01-06T12:38:12 0100',
expectedArrivalTime: '2022-01-06T12:37:32 0100',
forAlighting: true,
forBoarding: true,
notices: [],
predictionInaccurate: false,
quay: {
id: 'xxx',
name: 'xxx',
publicCode: 'P2',
situations: [],
stopPlace: [Object]
}
}
<script src="departures.js"></script>
<input type="button" onclick="write_bus()" value="Busstider"> <br>
<div id="bustime-kong"></div>
(為了節省一些空間,我洗掉了 2/3 的資料)
我很感激我能得到的每一點幫助!
uj5u.com熱心網友回復:
您不能將這樣的原始物件作為 DOM 文本插入。您必須使用特定的屬性,但如果您如此傾向于插入這樣的物件,請使用JSON.stringify()方法。
document.getElementById("bustime-kong").innerHTML = JSON.stringify(data);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
順便說一句,最好將<script>標簽放在末尾以確保在運行任何 JavaScript 之前加載 HTML。
uj5u.com熱心網友回復:
您可以創建一個函式,該函式將決議 json 并以表格形式列印,如下所示。
// this is the function write_bus() in my javascript file departures.js:
function write_bus() {
document.getElementById("bustime-kong").innerHTML = createTable(data);
}
// 'data' is a variable in javascript that contains the information I fetched from the client, and is what I am trying to show.It is on the following format:
const data = {
aimedArrivalTime: '2022-01-06T12:36:00 0100',
aimedDepartureTime: '2022-01-06T12:36:00 0100',
cancellation: false,
date: '2022-01-06',
destinationDisplay: {
frontText: 'xxx'
},
expectedDepartureTime: '2022-01-06T12:38:12 0100',
expectedArrivalTime: '2022-01-06T12:37:32 0100',
forAlighting: true,
forBoarding: true,
notices: [],
predictionInaccurate: false,
quay: {
id: 'xxx',
name: 'xxx',
publicCode: 'P2',
situations: [],
stopPlace: [Object]
}
}
function createTable(data){
var table = "<table>";
for(var key in data){
table ="<tr>";
table ="<td>" key "</td>";
table ="<td>" data[key] "</td>";
table ="</tr>";
}
table ="</table>";
return table;
}
<input type="button" onclick="write_bus()" value="Busstider"> <br>
<div id="bustime-kong"></div>
uj5u.com熱心網友回復:
由于它是您需要使用Json.stringify方法的資料陣列,
document.getElementById("bustime-kong").innerHTML = JSON.stringify(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406318.html
標籤:
