简体   繁体   English

Flask Ajax request.form

[英]Flask Ajax request.form

I want to do a flask project that sends with an ajax request a variable from js to flask.我想做一个 flask 项目,它发送一个 ajax 请求从 js 到 flask 的变量。 But when I run it, I don't get an error but the screen is showing None.但是当我运行它时,我没有收到错误,但屏幕显示无。

Flask Flask

from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/a",methods=['POST','GET'])
def home():
    a = None
    if request.method == 'POST':
        a = request.form['data']
        print(a)
    return render_template('new5.html',p=a)
if __name__ == '__main__':
    app.run(debug=True)

HTML HTML

<!DOCTYPE html>
<html>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
            var ab = 'asd'
            $.ajax({
                url: '/a', 
                type: 'POST',
                data : {'data':ab},
            })
        </script>
        <p>{{p}}</p>
    </body>
</html>

When I run it I get from the print('asd') asd in the flask console but on the page it returns None.当我运行它时,我从 flask 控制台中的print('asd') asd 得到,但在页面上它返回 None。 Also in the js console I get Failed to load resource: the server responded with a status of 404 (NOT FOUND) DevTools failed to load source map: Could not load content for chrome-extension://fheoggkfdfchfphceeifdbepaooicaho/sourceMap/chrome/scripts/content_scroll_mid_detection.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME .同样在 js 控制台我Failed to load resource: the server responded with a status of 404 (NOT FOUND) DevTools failed to load source map: Could not load content for chrome-extension://fheoggkfdfchfphceeifdbepaooicaho/sourceMap/chrome/scripts/content_scroll_mid_detection.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

Thanks.谢谢。

The problem here is that when you first visit /a you are using the GET flask endpoint to load the document where a is indeed None .这里的问题是,当您第一次访问/a时,您正在使用 GET flask 端点加载a确实为None的文档。 Then, when you make the $.ajax call, you are visiting the /a endpoint again but this time with method POST.然后,当您进行 $.ajax 调用时,您将再次访问/a端点,但这次使用的是 POST 方法。

The problem in the POST is that when you return the HTML template, it is going to be the result value of the $.ajax call. POST 中的问题是,当您返回 HTML 模板时,它将是$.ajax调用的结果值。 Since you didn't have the browser construct and POST a form and you aren't doing anything with the returned value of the AJAX call, you are seeing nothing change.由于您没有浏览器构造和 POST 表单,并且您没有对 AJAX 调用的返回值做任何事情,因此您看不到任何变化。

The main problem is you are mixing two approaches.主要问题是您正在混合两种方法。 Your POST handler is written like it expects the browser to submit a form while your Javascript is calling the POST handler as if it is a REST API.您的 POST 处理程序的编写方式就像它期望浏览器提交表单一样,而您的 Javascript 正在调用 POST 处理程序,就好像它是 REST API 一样。 I would focus on one approach or the other.我会专注于一种方法或另一种方法。

If you go the form route, you will need to render the form in the template and have your script code find the form on the page and submit() it.如果您使用 go 表单路由,则需要在模板中呈现表单并让您的脚本代码在页面上找到表单并submit()它。 In the AJAX form, you should probably return JSON instead and then use jQuery to update the DOM with the result.在 AJAX 表单中,您可能应该返回 JSON,然后使用 jQuery 用结果更新 DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM