【问题标题】:How to submit data to Flask from an Ajax call, and return its response in Flask from another Ajax call?如何从 Ajax 调用向 Flask 提交数据,并从另一个 Ajax 调用在 Flask 中返回其响应?
【发布时间】:2020-02-28 06:28:09
【问题描述】:

对不起,如果标题有点混乱。 StackOverflow 上的一位好心用户帮助我让我的 Flask 应用程序显示一些抓取的数据,只是现在我在函数中添加了一个参数,以便我可以抓取我想要搜索的数据。我有一个输入框,我希望能够从中获取数据,并将其作为字符串传递给 Flask 中的 python 函数

当前 HTML 端

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "utf-8">

    <title>NBA Data Web App</title>
</head>

<body>
    <script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
    <form id = "nameForm" method = "POST" role = "form">
        <input name = "text">
        <button id = "searchBtn"> Search </button>
    </form>

    <div id = "container"></div>

    <script type = "text/javascript">
        //Function to take place when our search button is clicked
        $('button#searchBtn').click(function() {
            $.ajax({
                url: '/_get_data',
                data: $('form').serialize(),
                type: 'POST',
                success: function(response) {
                    console.log = response;
                },
                error: function() {
                    alert('Failure in first Ajax call');
                }
            });

            /*Everything below this was working before, as I only made one ajax call when a button was pressed. Now, when I press the button, I want to pass its contents as a string to my scrape_data() function in Flask, and return, and display, its contents as shown below. */




            //Declare our list so we can print something, and loop through it later
            var data_list;
            //Variable for our HTML table
            var rowMax = 29, html = "<table><tr>";
            //Post request
            $.post('/_get_data', {
                //If done, do this
            }).done(function(response) {
                /* Assign our scraped data to our variable that was declared earlier, 
                which is turned into an array here in JS */
                data_list = response['data'];
                //Declare some variables for making our table
                var perRow = 1, count = 0, table = document.createElement("table"),
                row = table.insertRow();
                //Loop through the data and add it to the cells
                for (var i of data_list) {
                    //Insert a cell for each piece of data
                    var cell = row.insertCell();
                    //Add the data to the cell
                    cell.innerHTML = i;
                    //Increment our count variable
                    count++;
                    //If we have met our set number of items in the row
                    if (count % perRow == 0) {
                        //Start a new row
                        row = table.insertRow();
                    }
                }
                //Add the table to our container in our HTML
                document.getElementById("container").appendChild(table);
                //If request fails
            }).fail(function() {
                alert("request failed");
            });
        });
    </script>

</body>
</html>

Python(Flask)端

rom flask import Flask, render_template, jsonify, request, escape, url_for

#Get our lists to post
headers = data_headers()

#Start the flask app
app = Flask(__name__)

#Start page
@app.route('/')
def index():
    return render_template('index.html')

#What happens when our button is clicked
@app.route('/_get_data', methods = ['POST'])
def _get_data():
    text = request.form['text']

    #Here, I am trying to assign the contents of the input box of the form to a variable, so I can pass that variable as a parameter for my function.
    data = scrape_data(text)
    #Return the json format of the data we scraped
    return jsonify({'data' : data})

#Run the app
if __name__ == "__main__":
    app.run(debug = True)

我目前收到错误 405 方法不允许。我不确定我在第一个 Ajax 调用中的语法是否不正确,或者我是否需要将其分解为两个不同的 @app.route(urls),因为每个调用的方式都不同。

【问题讨论】:

  • 我写了一个答案,解释了如何通过 ajax 和 jquery 向 FLASK 发送数据。 You can take inspiration from that。如果遇到麻烦,请随时与我联系。
  • @Tobin 我需要把它分成两个电话吗?或者我可以把它放在上面吗
  • 您会注意到请求中有两个部分。第一个将数据发送到 Flask。 flask 根据这些数据执行操作,并通过 Ajax 返回结果。在这里您可以检索此数据并将其显示在您的页面上。所以从技术上讲,您不需要在代码中分离这些操作。
  • @Tobin 是的,我确实注意到了。我现在正在工作,我不确定我们是否在同一个时区,但我会在大约 8 小时后试一试。感谢您的帮助
  • @Tobin 我已经尝试按照您的教程进行操作,并且确实有所收获,但是,我现在遇到了 404 错误,正如我在最新的 StackOverflow 帖子中所解释的那样

标签: ajax python-3.x forms post flask


【解决方案1】:

如果你使用表单元素的method属性并且没有指定action,请求将被发送/。这里发生的事情是,当您单击搜索按钮时,它会从 ajax 向 '/''/_get_data' 发送两个帖子请求。在 Flask 路由中,如果您没有明确提供 methods=[],则该路由将仅允许 GET。从表单中删除方法属性,你不应该得到方法不允许的错误。

【讨论】:

    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2023-03-09
    • 2014-09-13
    相关资源
    最近更新 更多