jquery 将动态表的值发送到 flask 应用程序

kx1ctssn  于 2023-05-22  发布在  jQuery
关注(0)|答案(1)|浏览(179)

对不起这个乞丐的问题,我在JQuery中完全是个菜鸟,我有一个包含动态表的 flask 表单,我想把表的值发送到我的后端,它几乎完成了,但是我得到了secound td的值,如果我在first td中输入比萨饼,在secound td中输入20,我在我的后端得到了这个:{“”:“20”}这是我的html(我从我的cod中切下了大部分 flask 形式):

<div class="card-body">
                        <h1>New Cafe</h1>
                        <p class="text-muted">Add Your Cafe</p>

                        <form id="my-form" name="cafe" method="post" action=""
                              enctype="multipart/form-data">
                            {{ cafe_form.csrf_token }}
                            {{ ckeditor.load() }}
                            {{ ckeditor.config(name='about') }}
                            {{ cafe_form.name.label }}
                            <div class="input-group mb-3">
                                <span class="input-group-addon"></span>
                                {{ cafe_form.name(class="form-control") }}
                            </div>
                            <div id="data_container">
                                <div id="dynamic-fields">
                                    <table>
                                        <thead>
                                        <tr>
                                            <th>Menu item</th>
                                            <th>Menu item Price in USD $</th>
                                        </tr>
                                        </thead>
                                        <tbody class="p-4">
                                        <tr class="p-2">
                                            <td><input  type="text"></td>
                                            <td><input  type="text"></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </form>
                        <div class="pt-2 pb-2">
                   <button id="submit-btn" class="btn btn-outline-primary px-4">Submit</button>
                            <button id="add_rows" class="btn btn-outline-dark">+</button>
                        </div>
                    </div>

这是我添加额外行的js:

$("#add_rows").click(function () {
    // each click on the `+` button adds a row to the table
    $("#data_container tbody").append(`<tr><td><input type="text"></td><td><input type="text"></td></tr>`);
});
$("#submit_rows").click(function () {
    // `obj` for storing the inputs, and the `n` to make unrepeated keys
    let obj = {}, n = 0;
    // loop over the rows
    $("#data_container tbody tr").each(function (ind, tr) {
        // add an array to the object
        obj[`r${n}`] = [];
        // loop over the inputs of this row
        $(this).find("input").each(function (ind, input) {
            // add the value of the input to the array and make sure to remove any semicolon since
            // we will use it to separate the inputs
            const val = input.value.replace(/;/g, "");
            obj[`r${n}`].push(val);
        });
        // no need for the array, just join it to a string of values separated by semicolons
        obj[`r${n}`] = obj[`r${n}`].join(";");
        // increase the value of `n`
        n++;
    });
    // log the object to the console so you can see what we are sending
    console.log(obj);
    // send the data to the server, see the console for a logging message for success
    $.post("", obj, (data, status) => console.log("Status: " + status));
});

这是我尝试将数据发送到后端的部分:

const weburl = "/owner-new-cafe";
    document.getElementById('submit-btn').addEventListener('click', function (event) {
        event.preventDefault();
        submitForm();
    });

    function submitForm() {
        // Collect static form data
        const formData = new FormData(document.getElementById('my-form'));

        // Collect dynamic form data
        const dynamicData = [];
        $('#dynamic-fields tbody tr').each(function () {
            const row = {};
            $(this).find('input').each(function (ind, input) {
                row[this.name] = this.value;
            });
            dynamicData.push(row);
        });

        // Add dynamic form data to FormData object
        formData.append('dynamicData', JSON.stringify(dynamicData));
        document.getElementById("test").innerHTML = formData;

        // Send form data to Flask app using AJAX
        $.ajax({
            url: weburl,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                // Handle response from Flask app
            },
            error: function (xhr) {
                // Handle error
            }
        });

    }

请不要给予我只是回答我试着学习我想知道什么是我的mistakle和什么是最好的方式这样做非常感谢你

wkyowqbh

wkyowqbh1#

我解决了我的问题,一个问题是当我把按钮添加额外的行为我的动态表内的 flask 形式div,所以当我点击每个提交按钮 AJAX 发送两个后请求到我的后端,或者当用户只是想添加行再次发送一个后请求,它像一个提交按钮的行为一些其他问题是我不阿西斯的名称输入动态论坛感谢@Swati
因此,在本例中,我决定使用两个div,一个用于flask表单,另一个用于动态表单,如下所示:

新咖啡馆

添加您的咖啡馆
{{ cafe_form.csrf_token }} {{ ckeditor.load()}} {{ ckeditor.config(name='about')}} {{ cafe_form.name.label }} {{ cafe_form.name(class=“form-control”)}} {{ cafe_form.submit(id=“submit_rows”,class=“btn btn-outline-primary px-4”)}}菜单项菜单项价格USD $ +
然后使用这个jQuery代码以动态形式添加额外的行

// dynamic row
$("#add_rows").click(function() {
  // each click on the `+` button adds a row to the table
  $("#data_container tbody").append(`<tr><td><input class="input-group mb-3" 
     name="item" type="text"></td><td><input
 class="input-group mb-3" name="price" type="text"></td></tr>`);
});
$("#submit_rows").click(function() {
  // `obj` for storing the inputs, and the `n` to make unrepeated keys
  var obj = {}, n = 0;
  // loop over the rows
  $("#data_container tbody tr").each(function() {
    // add an array to the object
    obj[`r${n}`] = [];
    // loop over the inputs of this row
    $(this).find("input").each(function(ind, input) {
      // add the value of the input to the array and make sure to remove any semicolon since
      // we will use it to separate the inputs
      var val = input.value.replace(/;/g, "");
      obj[`r${n}`].push(val);
    });
    // no need for the array, just join it to a string of values separated by semicolons
    obj[`r${n}`] = obj[`r${n}`].join(";");
    // increase the value of `n`
    n++;
  });
  // log the object to the console so you can see what we are sending
  console.log(obj);
  // send the data to the server, see the console for a logging message for success
  $.post("", obj, (data, status) => console.log("Status: " + status));
});

在我的flask应用程序路由中,我使用request.form.items()获取两个列表的值,我认为我们可以通过使用to_dict将其更改为dict,在这种情况下,我的代码是:

@private.route('/<city>/owner-new-cafe', methods=["POST", "GET"])
@login_required
@confirmed_only
@owner_only
def owner_add_cafe(city):
    if request.method == "POST" and cafe_form.validate():
        print(request.form)
    for item in request.form.items():
        print(item)
    return "Job Done"

相关问题