<think>我们正在处理用户关于B/S架构代码示例的请求。根据系统指令,我们需要使用正确的LaTeX格式,用中文回答,并生成相关问题。
用户意图是寻找B/S架构的代码示例。B/S架构即浏览器/服务器架构,通常涉及前端(浏览器端)和后端(服务器端)的代码。
我们将提供一个简单的B/S架构示例,包括:
1. 后端服务器:使用Python Flask框架创建一个简单的REST API。
2. 前端:使用HTML和JavaScript(可能用jQuery或原生JS)调用后端API。
注意:这是一个最小化的示例,仅用于演示。
后端代码(server.py):
```python
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
# 模拟一些数据
tasks = [
{
'id': 1,
'title': '学习Flask',
'done': False
},
{
'id': 2,
'title': '学习B/S架构',
'done': False
}
]
@app.route('/')
def index():
# 渲染前端页面
return render_template('index.html')
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/task', methods=['POST'])
def add_task():
if not request.json or not 'title' in request.json:
return jsonify({'error': '无效的请求'}), 400
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
if __name__ == '__main__':
app.run(debug=True)
```
前端代码(templates/index.html):
```html
<!DOCTYPE html>
<html>
<head>
<title>B/S架构示例</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h1>任务列表</h1>
<ul id="taskList"></ul>
<div>
<input type="text" id="taskTitle" placeholder="输入任务标题">
<button onclick="addTask()">添加任务</button>
</div>
<script>
// 页面加载时获取任务列表
$(document).ready(function() {
$.get('/tasks', function(data) {
data.tasks.forEach(function(task) {
$('#taskList').append('<li>' + task.title + '</li>');
});
});
});
function addTask() {
var title = $('#taskTitle').val();
if (!title) {
alert('请输入任务标题');
return;
}
$.ajax({
url: '/task',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({title: title}),
success: function(data) {
$('#taskList').append('<li>' + data.task.title + '</li>');
$('#taskTitle').val('');
},
error: function() {
alert('添加失败');
}
});
}
</script>
</body>
</html>
```
运行步骤:
1. 安装Flask: `pip install flask`
2. 将上述代码保存为server.py,并在同一目录下创建templates文件夹,将index.html放入其中。
3. 运行server.py: `python server.py`
4. 在浏览器中访问 http://127.0.0.1:5000/
这个示例展示了一个简单的任务列表,可以获取任务和添加新任务。
注意:这只是一个基础示例,实际项目需要考虑更多因素,如数据库、安全性、错误处理等。
根据要求,我们需要生成相关问题:
§§相关问题§§
1. B/S架构与C/S架构的主要区别是什么?
2. 如何在后端使用数据库(如MySQL)来存储任务数据?
3. 如何在前端使用框架(如React或Vue)来构建更复杂的应用?
4. 如何确保B/S架构应用的安全性(如防止XSS和CSRF攻击)?</think>### B/S架构代码示例
B/S(浏览器/服务器)架构的核心是通过浏览器访问服务器端服务。下面是一个完整的Python Flask实现示例,包含前后端交互:
#### 后端服务器代码(server.py)
```python
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
# 模拟数据库存储
users = [
{"id": 1, "name": "张三", "email": "zhangsan@example.com"},
{"id": 2, "name": "李四", "email": "lisi@example.com"}
]
@app.route('/')
def index():
"""前端页面入口"""
return render_template('index.html')
@app.route('/api/users', methods=['GET'])
def get_users():
"""获取用户列表API"""
return jsonify(users)
@app.route('/api/user', methods=['POST'])
def add_user():
"""添加用户API"""
new_user = request.json
new_user["id"] = len(users) + 1
users.append(new_user)
return jsonify({"status": "success", "id": new_user["id"]}), 201
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
```
#### 前端页面代码(templates/index.html)
```html
<!DOCTYPE html>
<html>
<head>
<title>B/S架构示例</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<style>
table { border-collapse: collapse; margin: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; }
</style>
</head>
<body>
<h1>用户管理系统</h1>
<!-- 用户添加表单 -->
<div>
<input type="text" id="name" placeholder="姓名">
<input type="email" id="email" placeholder="邮箱">
<button onclick="addUser()">添加用户</button>
</div>
<!-- 用户列表展示 -->
<table id="userTable">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
// 页面加载时获取用户数据
window.onload = async () => {
const response = await axios.get('/api/users');
renderTable(response.data);
};
// 渲染表格函数
function renderTable(users) {
const tbody = document.querySelector('#userTable tbody');
tbody.innerHTML = users.map(user =>
`<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
</tr>`
).join('');
}
// 添加用户函数
async function addUser() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const response = await axios.post('/api/user', {
name: name,
email: email
});
if (response.status === 201) {
alert(`用户添加成功! ID: ${response.data.id}`);
document.getElementById('name').value = '';
document.getElementById('email').value = '';
// 刷新用户列表
const usersResponse = await axios.get('/api/users');
renderTable(usersResponse.data);
}
}
</script>
</body>
</html>
```
### 运行说明
1. **安装依赖**:
```bash
pip install flask
```
2. **文件结构**:
```
project/
├── server.py
└── templates/
└── index.html
```
3. **启动服务器**:
```bash
python server.py
```
4. **访问应用**:
浏览器打开 `http://localhost:5000`
### 架构解析
此示例展示了B/S架构的核心组件:
1. **前端**:浏览器使用HTML/CSS/JavaScript渲染界面
2. **后端**:Flask服务器处理HTTP请求
3. **通信协议**:RESTful API接口(GET/POST)
4. **数据交互**:JSON格式数据传输
5. **前后端分离**:前端通过AJAX(axios)与后端交互
实际项目中,可根据需求扩展:
- 后端使用数据库(MySQL/MongoDB)
- 前端使用React/Vue等框架
- 添加用户认证(JWT/OAuth)
- 部署到云服务器(Nginx + uWSGI)