如何通过Ajax+PHP将数组型输入框值插入数据表?
嘿,我明白你现在的问题啦——你用了数组型的输入框来收集多个作者的信息,但当前的Ajax代码只能拿到第一个输入框的值,没法把所有作者的数据都传去后端,对吧?这是因为你现在用的是单个ID选择器,而数组输入框需要批量获取所有值才行。
问题根源
你当前代码里的$("#author_fname_add").val()这种写法,只会匹配第一个ID为author_fname_add的元素(虽然你写了id="author_fname_add[]",但浏览器里重复ID是不规范的,它只会识别第一个),所以自然拿不到所有输入框的值。
解决方案步骤
- 批量获取数组输入框的所有值
用jQuery的属性选择器选中所有同名的输入框,再用.map()方法提取每个输入框的值,最后转成真实数组:
// 获取所有作者名的数组 var getbook_authorfname = $("[name='author_fname_add[]']").map(function() { return $(this).val().trim(); // 顺便去掉首尾空格,避免空值 }).get(); // 同理处理中间名和姓氏 var getbook_authormname = $("[name='author_mname_add[]']").map(function() { return $(this).val().trim(); }).get(); var getbook_authorlname = $("[name='author_lname_add[]']").map(function() { return $(this).val().trim(); }).get();
小提醒:建议把输入框的
id属性去掉,因为ID在HTML里必须是唯一的,重复的ID会导致DOM选择器出错,只用name属性就足够了。
- 修改Ajax的data参数
直接把这些数组传给后端,jQuery会自动把数组格式化成PHP能识别的格式:
data: { getbook_authorfname: getbook_authorfname, getbook_authormname: getbook_authormname, getbook_authorlname: getbook_authorlname, whatprocess: whatprocess },
- 后端PHP处理(adminfunctions.php)
在PHP里,你可以通过$_POST获取这些数组,然后循环插入每个作者的信息(记得做SQL防注入处理!):
if ($_POST['whatprocess'] == 'ADDBOOK') { $firstNames = $_POST['getbook_authorfname']; $middleNames = $_POST['getbook_authormname']; $lastNames = $_POST['getbook_authorlname']; // 循环遍历每个作者的数据 for ($i = 0; $i < count($firstNames); $i++) { $fname = $firstNames[$i]; $mname = $middleNames[$i]; $lname = $lastNames[$i]; // 这里写你的插入数据库逻辑,推荐用预处理语句防注入 // 示例: // $stmt = $pdo->prepare("INSERT INTO authors (fname, mname, lname) VALUES (?, ?, ?)"); // $stmt->execute([$fname, $mname, $lname]); } echo "SUCCESS"; }
修改后的完整Ajax代码
$(document).on("click", "#btn_addbook", function(e){ e.preventDefault(); // 获取所有作者的信息数组 var getbook_authorfname = $("[name='author_fname_add[]']").map(function() { return $(this).val().trim(); }).get(); var getbook_authormname = $("[name='author_mname_add[]']").map(function() { return $(this).val().trim(); }).get(); var getbook_authorlname = $("[name='author_lname_add[]']").map(function() { return $(this).val().trim(); }).get(); var whatprocess = "ADDBOOK"; $.ajax({ url: "adminfunctions.php", method: "POST", data: { getbook_authorfname: getbook_authorfname, getbook_authormname: getbook_authormname, getbook_authorlname: getbook_authorlname, whatprocess: whatprocess }, success: function(data) { var getdata = data.trim(); if (getdata == "SUCCESS") { swal({ title: 'Success!', text: '', type: 'success', confirmButtonClass: "btn btn-success", buttonsStyling: false }).then(function() { }); } else { swal({ title: 'Sorry for the inconvenience!', text: "There's a problem. Please contact the technical support for any concerns and questions." }); } } }); });
内容的提问来源于stack exchange,提问作者Corvus
相关产品推荐
相关产品推荐

