【问题标题】:How to pass data from html back to python file through an ajax script in order to render more data on the same page如何通过 ajax 脚本将数据从 html 传递回 python 文件,以便在同一页面上呈现更多数据
【发布时间】:2021-11-24 15:11:10
【问题描述】:

这是一个 Flask 问题。

我有一个下拉菜单和一个按钮。我希望按下按钮并将下拉列表的当前值发送回 python 函数。这个 python 函数会做一些事情并确定页面的进一步内容。

如果我重定向到一个新页面,我不需要使用任何 ajax 并且选择的值会很好地传递回 python 函数。

如果我不重定向而是尝试在同一页面上呈现所选值(这是我的要求),据我从本网站上的其他帖子中可以看出,我必须使用 Ajax 来调用 python 函数,但它没有捕获选定的值。

还请注意页面不应重新呈现的限制。

我真的很茫然,因为我不明白这两种情况之间的区别。任何帮助将非常感激。我对 python 有很好的经验,但是 Flask 和 html 对我来说非常新。

见下面的代码:

setup.py:

from app import app

# Data for initialisation of setup page
@app.route("/setup", methods=["GET", "POST"])
def create_models_dropdown():

    # Gets used to create the dropdown
    model_ids = list(range(1, 11))
    return render_template ("setup.html", ids=model_ids)

# Further data to be added on button click
@app.route('/test', methods=["GET", "POST"])
def test():

    ###
    # Debugging

    print(request.form)
    # When redirecting to a new page, this gives ImmutableMultiDict([('id_options', '5')]) (or whatever value is selected)
    # So the data is being returned

    # When staying on the same page (using the ajax script), this gives ImmutableMultiDict([]) so the dropdown value is not being returned
    
    ###
    
    model_id = request.form.get("id_options") # succeeds/fails as per comments above

    # Do something with the model_id
    return jsonify(result=(model_id or -1) * 2)

setup.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta charset="UTF-8" />
    <title>Wut</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
        integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous" />

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
        var $SCRIPT_ROOT = "";
    </script>

</head>


<body>
    <!-- 
        action="{{ url_for('test') }}" will render the new page and work as expected
        if i take it out, the result of running the script below will instead render
    -->
    <form action="{{ url_for('test') }}" method="post">
        <select name="id_options" width="300px">
            {% for id in ids %}
            <option value="{{ id }}" SELECTED>{{ id }}</option>
            {% endfor %}
        </select>
        <button class="get_result" type="button">Same page</button>
        <button class="get_result">New page</button>
    </form>
    <div class="result"></div>

</body>


<script>
    // This works in the sense that it calls the function
    $(document).on('click', '.get_result', function () {
        
        // Debugging
        // This was another attempt to get the value from the dropdown and pass it back which also didn't work
        // var model_id = $("#id_options").val();
        // console.log(model_id)
        //

        $.ajax({
            url: "/test",
            type: "get",
            // data: { model_id: model_id },
            success: function (response) {
                $(".result").html('<h1>' + response.result.toString() + '</h1>');
            },
        });
    });

</script>

</html>


【问题讨论】:

标签: python html flask


【解决方案1】:
  1. 您的选择没有 ID,只有名称。因此,您使用 id# 的 jquery 不正确。将id="id_options" 添加到您的select 元素中。

  2. 要获取选中的值,

    model_id = document.getElementById("id_options").value;

    model_id = $("#id_options").find("option:selected").val();
  1. 在您的 Ajax 代码中,您没有提交表单,这意味着您不能使用 request.form。而是尝试request.values.get("model_id", None)

【讨论】:

  • 是的,当我添加 id 时,console.log 工作,它也被传回后端。谢谢!
猜你喜欢
  • 2015-02-28
  • 2018-05-24
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2018-10-03
相关资源
最近更新 更多