烧瓶POST请求表单数据,无需刷新页面

时间:2020-05-28 22:15:18

标签: javascript python html flask

我正在构建一个小型Web应用程序,该应用程序允许用户通过几个表单输入字段(例如日期,交易金额,描述等)输入交易。每次用户单击“提交”按钮,都会创建一个新的表行,每个输入字段都有一列。除了构建该表之外,我还希望将输入数据发送到我的Flask应用程序。

我遇到的问题是,当用户单击“提交”时,页面将刷新并且所有表行都消失了。我为此尝试的解决方案是仅使用一个带有ID的<button type="button"></button>标记,当用户单击它时,我的Javascript代码将添加一个表行而不刷新页面。但是,这不起作用,因为它不会将数据发送到我的Flask应用程序。我也尝试在Javascript中使用sessionStorage.setItem,但是我不知道如何使它与我的特定代码一起使用,因为用户可以单击3次按钮进行3次不同的事务,并且每次页面刷新时都需要。

所以我的问题是,在还将表单输入数据发送到Flask应用程序的同时,如何在页面上创建和显示表格行?

为简单起见,这里我仅包含2个输入字段,但有8个。

HTML:

<form method="POST">
  <div class="list-group-item">
    <label>Date</label>
    <input class="form-control" id="datepicker" type="text" name=expDate value="">
  </div>
  <div class="list-group-item">
    <label>Amount Withdrawn</label>
    <input class="form-control" id="withAmount" type="text" name=expAmountWith value="">
  </div>
  <button id="submit-btn" type="submit" class="btn btn-light submit-btn">Submit</button>
</form>

JavaScript:

d3.selectAll('#submit-btn').on('click', buildTable);

function buildTable() {
    var dateInput = d3.select('#datepicker').property('value');
    var withAmount = d3.select('#withAmount').property('value');

    var tableArray = []
    tableArray.push(dateInput, withAmount)

    var row = d3.select('tbody').append('tr');

    tableArray.forEach(function(x) {

        var cell = row.append('td');
        cell.text(x);
    });

};

Python:

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def record_transaction():

    form = request.form

    if request.method == 'POST':
        expDate = request.form['expDate']
        expAmountWith = request.form['expAmountWith']

    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

2 个答案:

答案 0 :(得分:0)

因此,您需要使用ajax请求

d3.selectAll('#submit-btn').on('click', buildTable);
$.post( "/your-url", function( data ) { // data is the variable that the URL returns (that means you can't return render_template you have to return some raw data e.g string, json, int, etc)
     buildTable.append(data);
  });

我不确切知道您需要添加什么,所以我即兴创作。您需要做的是将您发送的数据追加到表中,就像您已经知道如何在JQuery中进行操作一样。我建议data将为JSON或列表。有关如何使用ajax发布请求visit the documentary

的更多信息

答案 1 :(得分:0)

您可以通过在JavaScript代码中获取表单元素,分配ID并使用getElementById来开始,或者以与其余代码更一致的方式开始(请参见使用jQuery,但我更喜欢香草JS)。然后,您可以将事件侦听器附加到表单的submit事件,然后使用<button type="button">,而不是使用preventDefault,以便页面不会刷新,并将数据发送到表单中的后端。打回来。这是一个示例:

form.addEventListener('submit', function(event) {
    event.preventDefault();    // prevent page from refreshing
    const formData = new FormData(form);  // grab the data inside the form fields
    fetch('/', {   // assuming the backend is hosted on the same server
        method: 'POST',
        body: formData,
    }).then(function(response) {
        // do something with the response if needed.
        // If you want the table to be built only after the backend handles the request and replies, call buildTable() here.
    });
});

我建议您在formData函数中使用相同的buildTable()对象,这样您就不必为每个元素分配一个ID并以此方式检索值,而是使用{{1 }}。

此外,更改您的Python函数以在formData.get(name)分支的末尾返回某些内容,这样它就不会将HTML返回给AJAX请求。在您的简单情况下,“ 204-无内容”也许是适当的。

我相信您知道如何用jQuery替换普通的JS

相关问题