javascript - 在表单中选择复选框时,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);
});
});
});
解决方案
推荐阅读
- java - 使用 Maven 将 gwt 客户端代码编译为 javascript
- generics - 如何在泛型函数中获取返回值?
- python - vlc player freezes GUI (python thread?)
- ruby-on-rails - Associating two columns in the same Model class to the same column in another Model - Rails
- google-cloud-platform - How to copy all folders from one Google Cloud instances to another?
- shell - Powershell Comparing two folders then copying it into another file
- firebase - AngularDart 5 和 Firebase 部署
- html - Do bootstrap takes "col-xs" automatically?
- javascript - Facebook SDK change display type in the FB.login()
- python - 如何使用 pandas.groupby() 识别相同的组?