1. 使用 Python 的 Flask 框架创建 Web 应用。
2. 编写 Python 代码处理请求。
3. 在 HTML 中通过 AJAX 调用 Python 代码。
示例代码:
from flask import Flask, jsonify
app = Flask(name)
@app.route('/calculate', methods=['POST'])
def calculate():
data = request.get_json()
result = data['a'] + data['b']
return jsonify({'result': result})
if name == 'main':
app.run()
HTML 代码:
<script>
function calculate() {
var a = 5;
var b = 3;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/calculate", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
console.log("Result:", response.result);
}
};
xhr.send(JSON.stringify({a: a, b: b}));
}
</script>
<button onclick="calculate()">Calculate</button>