Q: 承接之前的程式,做一個搜尋對話框
GPT回覆如下:
A:
要實現一個前端的搜尋框來按 stock_id
搜尋並展示結果,可以按照以下步驟完成:
在現有的前端目錄中添加搜尋功能,使用搜尋框提交 stock_id
,通過 API 返回數據並渲染到表格中。
bash
複製程式碼frontend/
├── index.html # 主頁面,包含搜尋框和表格
├── app.js # 更新 JavaScript 文件,處理搜尋邏輯
├── styles.css # 更新樣式文件
在 backend/app.py
中,更新 /api/company_financials
,支持根據 stock_id
查詢數據。
python
複製程式碼@app.route('/api/company_financials', methods=['GET'])
def get_company_financials():
"""
從資料庫中聯合查詢公司靜態與財務數據,支持 stock_id 搜索
"""
try:
# 獲取查詢參數
stock_id = request.args.get('stock_id')
# 基礎查詢語句
query = """
SELECT
c.stock_id,
c.company_short_name,
c.paid_in_capital,
f.revenue_million,
f.gross_margin_percent,
f.operating_profit_margin_percent,
f.pretax_profit_margin_percent,
f.net_profit_margin_percent
FROM twse_listed_companies c
JOIN financial_reports f ON c.stock_id = f.stock_id
"""
# 如果有 stock_id 查詢參數,添加 WHERE 條件
if stock_id:
query += " WHERE c.stock_id = :stock_id"
df = pd.read_sql(query, engine, params={"stock_id": stock_id})
else:
df = pd.read_sql(query, engine)
# 返回 JSON 結果
return jsonify(df.to_dict(orient='records'))
except Exception as e:
return jsonify({"error": str(e)}), 500
這樣,API 可以支持按 stock_id
搜索,例如:
arduino
複製程式碼http://127.0.0.1:5000/api/company_financials?stock_id=2330
在 frontend/index.html
中,添加搜尋框和表格。
html
複製程式碼<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Company Financial Search</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Company Financials</h1>
<!-- 搜尋框 -->
<div class="search-container">
<input type="text" id="search-input" placeholder="Enter Stock ID" />
<button id="search-button">Search</button>
</div>
<!-- 表格 -->
<table id="financials-table">
<thead>
<tr>
<th>Stock ID</th>
<th>Company Short Name</th>
<th>Paid-in Capital</th>
<th>Revenue (Million)</th>
<th>Gross Margin (%)</th>
<th>Operating Profit Margin (%)</th>
<th>Pretax Profit Margin (%)</th>
<th>Net Profit Margin (%)</th>
</tr>
</thead>
<tbody>
<!-- Data will be inserted here -->
</tbody>
</table>
<script src="app.js"></script>
</body>
</html>
在 frontend/app.js
中實現搜尋功能,將 API 結果動態插入表格。
javascript
複製程式碼// Function to fetch and render data
function fetchAndRenderData(stockId = null) {
// API URL
let apiUrl = 'http://127.0.0.1:5000/api/company_financials';
if (stockId) {
apiUrl += `?stock_id=${stockId}`;
}
// Fetch data from API
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const tableBody = document.querySelector('#financials-table tbody');
tableBody.innerHTML = ''; // 清空現有的表格數據
// 如果沒有結果
if (data.length === 0) {
const row = document.createElement('tr');
row.innerHTML = `<td colspan="8">No results found</td>`;
tableBody.appendChild(row);
return;
}
// 插入每筆數據
data.forEach(company => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${company.stock_id}</td>
<td>${company.company_short_name}</td>
<td>${company.paid_in_capital || 'N/A'}</td>
<td>${company.revenue_million || 'N/A'}</td>
<td>${company.gross_margin_percent || 'N/A'}</td>
<td>${company.operating_profit_margin_percent || 'N/A'}</td>
<td>${company.pretax_profit_margin_percent || 'N/A'}</td>
<td>${company.net_profit_margin_percent || 'N/A'}</td>
`;
tableBody.appendChild(row);
});
})
.catch(error => console.error('Error fetching data:', error));
}
// Initial load: fetch all data
fetchAndRenderData();
// Search button event listener
document.getElementById('search-button').addEventListener('click', () => {
const stockId = document.getElementById('search-input').value.trim();
fetchAndRenderData(stockId);
});
在 frontend/styles.css
中為搜尋框添加樣式:
css
複製程式碼body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
text-align: center;
}
.search-container {
text-align: center;
margin-bottom: 20px;
}
#search-input {
padding: 10px;
width: 300px;
font-size: 16px;
}
#search-button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
#search-button:hover {
background-color: #45a049;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
}
th {
background-color: #f4f4f4;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
stock_id
,例如 2330
。stock_id
的相關數據。