python文件用ajax方式请求 摸个接口
时间: 2024-01-31 14:04:18 浏览: 76
要用 AJAX 方式请求一个接口,需要使用前端技术实现。以下是一个 Python Flask 后端的示例代码,可以提供一个简单的接口供前端调用:
```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/hello', methods=['POST'])
def hello():
name = request.json.get('name')
return jsonify({'message': f'Hello, {name}!'})
if __name__ == '__main__':
app.run()
```
这个接口可以接收一个 POST 请求,请求体中包含一个 JSON 对象,其中的 `name` 字段是一个字符串。返回一个 JSON 对象,其中的 `message` 字段是一个字符串,包含了问候语和 `name` 字段的值。
在前端中,你可以使用 jQuery 发送 AJAX 请求:
```javascript
$.ajax({
url: '/api/hello',
method: 'POST',
data: JSON.stringify({name: 'World'}),
contentType: 'application/json',
success: function(response) {
console.log(response.message);
},
error: function(xhr, status, error) {
console.error(error);
}
});
```
这个代码片段会向 `/api/hello` 发送一个 POST 请求,请求体中包含一个 JSON 对象 `{name: 'World'}`,并且设置请求头中的 `Content-Type` 为 `application/json`。如果请求成功,控制台会输出一个问候语和 `World`。如果请求失败,控制台会输出错误信息。
阅读全文
相关推荐


















