股票实时行情查询 - 前端代码示例
<!DOCTYPE html>
<html>
<head>
<title>股票查询</title>
<meta charset='utf-8'>
<style type='text/css'>
table {
border-collapse: collapse;
}
td, th {
padding: 5px;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>股票实时行情查询</h1>
<div>
<label for='stockCode'>股票代码:</label>
<input type='text' id='stockCode'>
<button id='searchBtn'>查询</button>
</div>
<div id='tableWrapper'></div>
<pre><code><script type='text/javascript'>
const searchBtn = document.querySelector('#searchBtn');
searchBtn.addEventListener('click', () => {
const stockCode = document.querySelector('#stockCode').value;
const apiUrl = `https://api.doctorxiong.club/v1/stock/get?code=${stockCode}`;
fetch(apiUrl)
.then(res => res.json())
.then(data => {
const tableWrapper = document.querySelector('#tableWrapper');
if (data.code === 200) {
const stockData = data.data;
const tableHtml = `
<table>
<thead>
<tr>
<th>股票代码</th>
<th>股票名称</th>
<th>当前价格</th>
<th>昨收</th>
<th>今开</th>
<th>成交量(手)</th>
</tr>
</thead>
<tbody>
<tr>
<td>${stockData.code}</td>
<td>${stockData.name}</td>
<td>${stockData.now}</td>
<td>${stockData.close}</td>
<td>${stockData.open}</td>
<td>${stockData.volume}</td>
</tr>
</tbody>
</table>
`;
tableWrapper.innerHTML = tableHtml;
} else {
tableWrapper.innerHTML = `<p>${data.message}</p>`;
}
})
.catch(err => {
console.error(err);
const tableWrapper = document.querySelector('#tableWrapper');
tableWrapper.innerHTML = '<p>查询失败,请稍后再试。</p>';
});
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/nJBj 著作权归作者所有。请勿转载和采集!