首页 > 解决方案 > 在表单中选择复选框时,Ajax 调用不起作用

问题描述

我正在使用 django 框架开发一个表单。我有一个表格,其中有一个表格,然后是表格中的一些复选框。我正在将该数据收集到字典中并将其传递给我的 django 函数。如果我在不选择复选框的情况下提交表单,它工作正常。但是当我选择复选框时,数据不会发布到 views.py 文件中。我看到正在使用 console.log 将数据填充到字典中。

需要这方面的指导。

我的html:

<table>
    .....
    .....
</table>
<div class="checkbox">
    <label><input type="checkbox" name="run_prep" value="">Run Prep</label>
</div>
<div class="checkbox">
    <label><input type="checkbox" name="run_post"value="">Run Post</label>
</div>`enter code here`
<div class="checkbox">
    <label><input type="checkbox" name="run_reports" value="">Run Reports</label>`enter code here`
</div>

下面是我的js代码:

$(document).ready(function(){
    $("form").submit(function(e){
        e.preventDefault();

        var data = {};
        form_data = []
        $("tr", "tbody").each(function(row){
            var count_row = true;
            $("input", this).each(function(idx, inp){
                if (!($(this).val())){
                    count_row = false;
                }
            });
            $("select", this).each(function(idx, inp){
                if (!($(this).val())){
                    count_row = false;
                }
            });
            if (count_row){
                row_data = {};
                $("input", this).each(function(idx, inp){
                    row_data[$(this).attr("name")] = $(this).val();
                });
                $("select", this).each(function(idx, inp){
                    row_data[$(this).attr("name")] = $(this).val();
                });
                var id = $(this).attr("id");
                data[id] = row_data;
                form_data.push(data);
                data = {};
            }
        });
        run_check = {};
        $("input[type=checkbox]", this).each(function () {
            if (this.checked) {
                run_check[$(this).attr("name")] = 1;
            }
        });
        var chkname = "run-check"
        data[chkname] = run_check;
        form_data.push(data);
        var csrftoken = Cookies.get('csrftoken');
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
        console.log(JSON.stringify(form_data))
        $.ajax({
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(form_data)
        }).then(function(data){
            console.log(data);
            location.replace(data.redirect);
        });
    });
});

标签: javascriptajaxdjango

解决方案


推荐阅读