我有最简单的烧瓶应用程序:
app = Flask(__name__)
@app.route('/python/', methods = ['GET','POST'])
def index():
return "Hello World"
if __name__ == "__main__":
app.run(debug=True)
以及一个非常简单的网页,带有文本区域和按钮。
<textarea id="mytextarea">Some text...</textarea>
<p> Click the button </p>
<button type="button" onclick="myFunction()"> Click here</button>
<p id="demo"> </p>
我想要做的是,当单击按钮时,使用脚本将 Flask 的响应放在网页上。我尝试了以下方法,但它不起作用。当我点击按钮时什么也没有发生。我究竟做错了什么?
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:5000/python/", true);
xhttp.send();
var x = xttp.response;
document.getElementById("demo").innerHTML = x;
}
</script>
(我是初学者)。
请参阅下面的代码并查看XMLHttpRequest.onreadystatechange https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange详细信息
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "http://127.0.0.1:5000/python/", true);
xhttp.send();
}
</script>
如果您从 Flask 应用程序发送 html,则不会出现 Cors 问题(请参阅示例代码),您需要从 Flask 导入 render_template。
@app.route('/')
def hello_world():
return render_template('index.html')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)