如何用jQuery Ajax优雅发送输入数组?分组结构实现求助
问题核心原因
你用.val()只能获取第一个匹配元素的值,要获取所有元素的数组,必须用.map()遍历所有匹配项,再通过.get()转换为原生数组。
方案1:生成单独的ids、names、scores数组
对应你想要的第一种$_REQUEST结构:
// 提取所有name输入的值数组 let input_names = $('input[name^="name_"]').map(function() { return this.value.trim(); }).get(); // 提取所有score输入的值数组 let input_scores = $('input[name^="score_"]').map(function() { return this.value.trim(); }).get(); // 从name属性中提取关联ID数组 let ids = $('input[name^="name_"]').map(function() { return this.name.match(/\[(\d+)\]/)[1]; }).get(); // 发送AJAX请求 $.ajax({ url: "../util/funcs.php", async: true, data: { a: "backendFunction", ids: ids, input_names: input_names, input_scores: input_scores }, done: function(data) { console.log("Success"); }, fail: function() { console.log("Error"); }, always: function() { // alert( "complete" ); } });
后端PHP接收后,$_REQUEST会得到:
[ 'a' => 'backendFunction', 'ids' => ['1', '2', '3'], 'input_names' => ['alex', 'john', ...], 'input_scores' => ['30', '70', ...] ]
方案2:生成按ID分组的理想结构
对应你想要的第二种$_REQUEST结构,直接把每个ID对应的name和score组合成对象:
let students = {}; // 获取所有唯一的关联ID let ids = $('input[name^="name_"]').map(function() { return this.name.match(/\[(\d+)\]/)[1]; }).get(); // 遍历ID,匹配对应的name和score输入 ids.forEach(id => { let name = $(`input[name="name_[${id}]"]`).val().trim(); let score = $(`input[name="score_[${id}]"]`).val().trim(); // 跳过空值项(可选) if (name || score) { students[id] = { name: name, score: score }; } }); // 发送AJAX请求 $.ajax({ url: "../util/funcs.php", async: true, data: { a: "backendFunction", students: students }, done: function(data) { console.log("Success"); }, fail: function() { console.log("Error"); }, always: function() { // alert( "complete" ); } });
后端PHP接收后,$_REQUEST['students']会自动解析为:
[ '1' => ['name' => 'alex', 'score' => '30'], '2' => ['name' => 'john', 'score' => '70'], ... ]
针对student[1][name]这种HTML结构的简化方案
如果改用这种命名规范,jQuery可以用serializeArray()快速序列化,PHP会自动解析为多维数组,无需手动处理:
// 序列化所有student相关的输入 let formData = $('input[name^="student["]').serializeArray(); // (可选)转换为更直观的对象结构 let studentsObj = {}; formData.forEach(item => { // 解析name属性中的ID和字段名 let matches = item.name.match(/student\[(\d+)\]\[(\w+)\]/); let id = matches[1]; let field = matches[2]; if (!studentsObj[id]) { studentsObj[id] = {}; } studentsObj[id][field] = item.value.trim(); }); // 发送请求 $.ajax({ url: "../util/funcs.php", async: true, data: { a: "backendFunction", students: studentsObj }, done: function(data) { console.log("Success"); }, fail: function() { console.log("Error"); }, always: function() { // alert( "complete" ); } });
内容的提问来源于stack exchange,提问作者Seltonu
相关产品推荐
相关产品推荐

