帮我制作类似于奶酪单词的单词卡片页面,单词从mysql数据库调用,写前后端的代码
时间: 2024-10-15 18:25:56 浏览: 51
为了创建一个类似奶酪单词的单词卡片页面,我们首先需要设计前端界面展示单词,并通过后端从MySQL数据库中获取数据。下面是简化的前后端代码示例:
**前端(HTML + JavaScript,假设使用Vue.js或React):**
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>奶酪单词卡片</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="word-cards">
<div v-for="(word, index) in words" :key="index">
<div class="card">
<h3>{{ word.word }}</h3>
<p>定义: {{ word.definition }}</p>
<button @click="checkAnswer(index)">检查答案</button>
</div>
</div>
</div>
<script>
new Vue({
el: '#word-cards',
data() {
return { words: [] }
},
async created() {
try {
const response = await fetch('api/getWords');
if (response.ok) {
this.words = await response.json();
} else {
console.error('Error fetching words:', response.status);
}
} catch (error) {
console.error('Error:', error);
}
},
methods: {
checkAnswer(index) {
// 在这里添加检查答案的功能,比如显示对错提示等
}
}
});
</script>
</body>
</html>
```
**后端(Node.js with Express和MySQL连接库):**
```javascript
const express = require('express');
const mysql = require('mysql');
const app = express();
// 创建MySQL连接池
const pool = mysql.createPool({
host: 'your_host',
user: 'your_user',
password: 'your_password',
database: 'your_database'
});
app.get('/getWords', async (req, res) => {
try {
const connection = await pool.getConnection();
const [rows] = await connection.query('SELECT * FROM your_words_table');
connection.release(); // 确保关闭连接
res.json(rows);
} catch (err) {
console.error('Error getting words from DB:', err);
res.status(500).send('Error retrieving words.');
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
```
请注意,这只是一个基本示例,实际项目中可能需要处理更复杂的错误处理、数据验证以及用户交互体验。同时,确保已经安装了相应的依赖包。
阅读全文