黄金历史数据
日期
|
开盘价
|
最高价
|
最低价
|
收盘价
|
style.css:
css
body {font-family: Arial, Helvetica, sans-serif;background-color: f0f0f0;
}.container {display: flex;gap: 2rem;padding: 2rem;
}.left-panel {flex: 1;
}.right-panel {flex: 1;
}h2 {font-size: 1.5rem;margin-bottom: 1rem;
}.price {font-size: 2rem;font-weight: bold;margin-bottom: 1rem;
}refresh-button {
cursor: pointer;padding: 0.5rem 1rem;background-color: 007bff;color: fff;border: 1px solid 007bff;border-radius: 5px;
}.chart-container {height: 300px;
}.chart {width: 100%;height: 100%;
}.history-table {width: 100%;border-collapse: collapse;
}th, td {padding: 0.5rem;border: 1px solid ccc;
}script.js:
javascript
const realTimePriceElement = document.getElementById("real-time-price");
const refreshButton = document.getElementById("refresh-button");
const historyDataElement = document.getElementById("history-data");
const goldChart = new Chart(document.getElementById("gold-chart"), {type: "line",data: {labels: [],datasets: [{label: "金价",data: [],backgroundColor: "rgba(255, 215, 0, 0.2)",borderColor: "rgba(255, 215, 0, 1)",borderWidth: 1,},],},options: {scales: {y: {beginAtZero: true,},},},
});const fetchGoldData = async () => {try {// 获取实时金价const response = await fetch("https://www.sge.com.cn/sjzx/ quotations/goldtjsj.asmx/GetGoldTjsj_JSON");const data = await response.json();realTimePriceElement.textContent = `${data.goldtjsj.tradeprice} 元/克`;// 获取历史金价const historyResponse = await fetch("https://www.sge.com.cn/sjzx/ quotations/goldtjsj.asmx/GetYesterdayGoldTjsj_JSON");const historyData = await historyResponse.json();historyDataElement.innerHTML = "";for (const day of historyData.goldtjsj) {const row = document.createElement("tr");const dateElement = document.createElement("td");dateElement.textContent = day.tradedate;const openPriceElement = document.createElement("td");openPriceElement.textContent = day.openprice;const highestPriceElement = document.createElement("td");highestPriceElement.textContent = day.highestprice;const lowestPriceElement = document.createElement("td");lowestPriceElement.textContent = day.lowestprice;const closePriceElement = document.createElement("td");closePriceElement.textContent = day.closeprice;row.appendChild(dateElement);row.appendChild(openPriceElement);row.appendChild(highestPriceElement);row.appendChild(lowestPriceElement);row.appendChild(closePriceElement);historyDataElement.appendChild(row);}// 更新图表goldChart.data.labels = historyData.goldtjsj.map((day) => day.tradedate);goldChart.data.datasets[0].data = historyData.goldtjsj.map((day) => day.closeprice);goldChart.update();} catch (error) {console.error(error);}
};fetchGoldData();refreshButton.addEventListener("click", fetchGoldData);