使用ajax前后端连接交互代码
时间: 2024-04-03 10:35:34 浏览: 58
下面是使用 AJAX 进行前后端连接交互的示例代码:
前端代码:
```javascript
const fetchUser = (id) => {
$.ajax({
url: `http://localhost:8000/api/users/${id}`,
type: 'GET',
dataType: 'json',
success: (response) => {
console.log(response);
},
error: (xhr, status, error) => {
console.error(error);
}
});
};
const createUser = (user) => {
$.ajax({
url: 'http://localhost:8000/api/users',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(user),
success: (response) => {
console.log(response);
},
error: (xhr, status, error) => {
console.error(error);
}
});
};
```
后端代码:
```python
from flask import Flask
from flask import jsonify, request
app = Flask(__name__)
users = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Charlie'},
]
@app.route('/api/users/<int:id>', methods=['GET'])
def get_user(id):
for user in users:
if user['id'] == id:
return jsonify(user)
return jsonify({'error': 'User not found'})
@app.route('/api/users', methods=['POST'])
def create_user():
user = request.json
user_id = len(users) + 1
user['id'] = user_id
users.append(user)
return jsonify(user)
if __name__ == '__main__':
app.run(port=8000)
```
在上面的示例中,前端使用 jQuery 库进行 AJAX 请求,并向 Flask 框架开发的后端应用提供的 RESTful API 发送请求。后端应用接收请求并返回 JSON 格式的数据。在后端应用中,使用 Flask 框架创建了两个路由,分别用于获取和创建用户数据。
阅读全文
相关推荐















