form.serialize()发送空对象 - Django表单

时间:2017-08-01 03:56:35

标签: javascript jquery ajax django forms

我的 AJAX查询在按钮点击时发送一个空对象 Object { } - 它应该是发送表单数据。

我有一个带复选框的表单。它呈现和功能,HTML就像这样:

<form method="post" action="" data-id="filter-form">

//This is from Django's CSRF token
<form  method="post" >
<input type='hidden' name='csrfmiddlewaretoken' value=.../>

<div class="form-group"> <div id="div_id_vacant" class="checkbox"> 
  <label for="id_vacant" class="">Is Vacant</label>
  <input type="checkbox" name="vacant" class="checkboxinput" id="id_vacant" />
</div></div>

...more of the same inputs...

</form>
</form>

<hr/>

<button id="search-btn" class="btn btn-info" data-filter-leads-url="/leads/ajax/filter">Search</button>
<button id="download-btn" class="btn btn-default" data-filter-leads-url="/leads/csv">Download</button>

我也有一些JQuery的东西。读取表单并通过post向Django视图发送AJAX请求是假设。它看起来像这样:

{Django CSRF code here}

var searchBtn = $("#search-btn");
searchBtn.click(function () {
    var form = $("#filter-form");

    $.ajax({
        url: searchBtn.attr("data-filter-leads-url"),
        method: "POST",
        data: form.serialize(),
        dataType: 'json',
        success: function (data) {
            console.log(data)
        },
        error: function (data) {
            console.log("There was an error.");
            console.log(data.error())
        }
    });

});

我也尝试过:

var formData = new FormData(form[0]);

它也会发送一个空对象。

通过 Django视图打印request.POSTconsole.log(form.serlialize())命令以及console.log(formData)命令确认空对象。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您的表单正在使用data-id,在其中添加ID并重试。

<form method="post" action="" data-id="filter-form" id='filter-form'>

希望它有所帮助。

最诚挚的问候,

Hatjhie

答案 1 :(得分:1)

替换你的代码:

<强> HTML:

<form method="post" action="" data-id="filter-form" id="filter-form">
//This is from Django's CSRF token
<input type='hidden' name='csrfmiddlewaretoken' value=.../>

<div class="form-group"> <div id="div_id_vacant" class="checkbox"> 
  <label for="id_vacant" class="">Is Vacant</label>
  <input type="checkbox" name="vacant" class="checkboxinput" id="id_vacant" />
</div></div>

...more of the same inputs...

</form>

<hr/>

<button id="search-btn" class="btn btn-info" data-filter-leads-url="/leads/ajax/filter">Search</button>
<button id="download-btn" class="btn btn-default" data-filter-leads-url="/leads/csv">Download</button>

<强> jQuery的:

{Django CSRF code here}

var searchBtn = $("#search-btn");
searchBtn.click(function () {
    var form = $("#filter-form");
    $.ajax({
        url: searchBtn.attr("data-filter-leads-url"),
        method: "POST",
        data: form.serialize(),
        dataType: 'json',
        success: function (data) {
            console.log(data)
        },
        error: function (data) {
            console.log("There was an error.");
            console.log(data.error())
        }
    });

});