【发布时间】:2017-01-13 17:48:35
【问题描述】:
我正在尝试实现一个功能,网站管理员可以通过选中复选框然后单击 SELECTED 按钮一次删除多个内容,如下所示。
这意味着我必须一次提交多个表单,并且我在网上查找了一种解决方法,但我似乎无法让它发挥作用。单击 SELECTED 按钮后,将调用 deleteRecords()。代码如下:
function deleteRecords() {
//--- Creating array of selected rows ---
var arrayOfIDs;
arrayOfIDs = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
//-- Declaring variables ---
var delFlagForm; //-- form
var action; //-- form action
var formID; //-- form id
var submitFormStr; //-- string of forms' id's
//--- Creating form for each row selected ---
for (var i = 0; i < arrayOfIDs.length; i++) {
delFlagForm = document.createElement("form"); //-- Creating form
action = "/delete_flag/" + arrayOfIDs[i]; //-- Creating action link
formID = 'form' + i; //-- Creating id (form0, form1, etc)
delFlagForm.setAttribute("id", formID); //-- Assigning id to form
delFlagForm.setAttribute("method", "post"); //-- Assigning method to form
delFlagForm.setAttribute("action", action); //-- Assigning action to form
//--- Creating string of forms' id's
if (i != 0) submitFormStr += ' #' + formID;
else submitFormStr = '#' + formID;
}
//--- Submiting forms at once ---
//-- For the table shown above, submitFormStr = "#form0 #form1"
$(submitFormStr).submit(); // = $('#form0 #form1').submit();
}
显然上面显示的代码应该是提交 form0 和 form1 从而删除选定的记录。但是,由于某种原因,表单没有提交,什么也没有发生。
你能发现任何错误吗?
----------- 编辑 - 解决方案 -----------
为了解决这个问题,我尝试使用 AJAX 忽略请求,现在正在工作。新代码如下所示:
<script>
function deleteRecords() {
var arr;
arr = $('#table-style').find('[type="checkbox"]:checked').map(function(){
return $(this).closest('tr').find('td:nth-child(2)').text();
}).get();
var delFlagForm;
var action;
var formID;
var submitFormStr;
for (var i = 0; i < arr.length; i++) {
delFlagForm = document.createElement("form");
action = "/delete_flag/" + arr[i];
formID = 'form' + i;
delFlagForm.setAttribute("id", formID);
delFlagForm.setAttribute("method", "post");
delFlagForm.setAttribute("action", action);
ignoreRequest(delFlagForm);
}
}
function ignoreRequest(form) {
var formID = $('#' + form.id);
var action = form.action;
$.ajax({
type: "POST",
url: action, //action
data: formID,
success: function (data) {
location.reload();
},
error: function(jqXHR, text, error){
console.log(error);
}
});
return false;
}
</script>
【问题讨论】:
-
$(submitFormStr).submit();而不是$('submitFormStr').submit(); -
@DanielCorzo 是的,没有注意到这个缺陷,但它无论如何都不起作用。那行代码之后什么都没有发生
-
if (i != 0) submitFormStr += ', #' + formID;
标签: javascript form-submit multiple-forms