使用jquery和ajax删除空表单输入后,阻止空表单输入向数据库提交
美好的一天,我一直在这个网站上阅读所有可能的问题和答案,我知道我几乎得到了正确的答案,但似乎这里的一些建议对我不起作用。 我有一个动态表单,用户可以添加和删除文本字段,并通过ajax和php提交请求。 该表单由两个必需的文本字段和按钮组成,用于添加和删除另一个字段(除了两个必填字段)。 即使不使用其他额外字段,用户也可以提交表单。
我的问题是,如果我按下添加按钮,稍后决定删除它,即使按下删除按钮后,我在数据库中的相应表中得到一个’0’值。
这是我的HTML:
这是我的AJAX
$(document).ready(function() { $("#save-button").click(function() { var subject = $("input#subject-field").val(); if (subject == "") { $('#status-message').css({ "color": "#ec3f8c" }); $('#status-message').html('Please fill the subject fields'); return false; } var section = $("input#section-field").val(); if (section == "") { $('#status-message').css({ "color": "#ec3f8c" }); $('#status-message').html('Please fill the section fields'); return false; } var studid = []; $('input[name="studid[]"]').map(function() { studid.push($(this).val()); }); var dataString = 'subject=' + subject + '§ion=' + section + '&studid=' + studid; $.ajax({ type: "POST", url: 'save.php', data: dataString, dataType: "html", success: function(data) { $("input#subject-field").val(''); $("input#section-field").val(''); $("input#field-wrap").remove(); $("#status-message").css({ "color": "#39b1c6" }); $("#status-message").html('Save successfully'); $("#status-message").fadeOut(2000); }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError); } }); return false; }); });
我的Jquery柜台
$(document).ready(function() { var counter = 0; $(".add-field").click(function() { counter += 1; $("#student-box-wrap").append('' + counter + '. Student ID: '); }); $(".remove-field").click(function() { if (counter == 0) { alert("Nothing to remove!"); } else { $(".field-wrap-" + counter + "").remove(); counter--; } }); });
还有我的PHP
我用过!在我的PHP中空,我得到相同的结果。 如果我根本不按添加按钮,我没有任何问题。 它只是在按下它时,甚至在删除它之后,ajax中的变量似乎携带一个空数据到数据库。
我认为你的问题是,在你的PHP中,你调用$studid = (explode(",", $_POST['studid']));
在检查是否设置了值之前。
来自explode()
的文档explode()
如果分隔符是空字符串(“”),则explode()将返回FALSE。 如果分隔符包含未包含在字符串中的值并且使用了负限制,则将返回空数组, 否则将返回包含字符串的数组 。
实际上,您在空字符串上调用explode()
并返回空字符串。
在PHP
,尝试在if语句中移动explode()
,然后检查它是否设置为:
另外,在你的jquery中,改变:
var dataString = 'subject=' + subject + '§ion=' + section + '§ion=' + section;
至:
// only add `studid` if there is one or more present var studidStr = studid != '' ? '&studid=' + studid : ''; var dataString = 'subject=' + subject + '§ion=' + section + studidStr;