使用Flask返回来修改网页 [英] Using Flask return to modify a webpage

查看:902
本文介绍了使用Flask返回来修改网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  app = Flask(__ name__)
@ app.route(' / python /',methods = ['GET','POST'])
def index():
返回Hello World
if __name__ ==__main__:
app.run(debug = True)

以及一个非常简单的带有文本区域和按钮的网页。

 < textarea id =mytextarea>一些文字...< / textarea> 
< p>点击按钮< / p>
< button type =buttononclick =myFunction()>点击此处< /按钮>
< p id =demo> < / p为H.

我想要做的是在按钮上使用脚本将Flask的响应放在网页上被点击。我尝试了以下,但它不起作用。当我点击按钮时没有任何反应。我做错了什么?

 < script> 
函数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 了解详情

 < script> 
函数myFunction(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange =函数(){
如果(xhttp.readyState === XMLHttpRequest.DONE){
的document.getElementById( 演示)的innerHTML = xhttp.responseText。
}
};
xhttp.open(POST,http://127.0.0.1:5000/python/,true);
xhttp.send();
}
< / script>

如果您从烧瓶应用程序发送html代码,请参阅示例代码,来自flask的render_template。

  @ app.route('/')
def hello_world():
return render_template(' index.html')


I have the simplest flask app:

app = Flask(__name__)
@app.route('/python/', methods = ['GET','POST'])
def index():
    return "Hello World"
if __name__ == "__main__":
    app.run(debug=True)

and a very simple webpage with a text area and a button.

<textarea id="mytextarea">Some text...</textarea>
<p> Click the button </p>
<button type="button" onclick="myFunction()"> Click here</button>
<p id="demo"> </p>

What I want to do is to put the response from Flask on the webpage using a script when the button is clicked. I tried the following but it doesn't work. Nothing happens when I click the button. What am I doing wrong?

<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>

(I am a beginner).

解决方案

see the code below and review the XMLHttpRequest.onreadystatechange for detail

<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>

no cors issue if you send the html from your flask app see the example code, you need to import render_template from flask.

@app.route('/')
def hello_world():
    return render_template('index.html')

这篇关于使用Flask返回来修改网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆