You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ajax & JSP实现多行数据插入:解决逗号分隔值插入问题

问题:多行数据内联插入时,数据被逗号分隔存入单条记录,需改为逐条插入

当前通过Ajax+JSP实现多行学生数据内联插入功能,数据提交后会以逗号分隔的形式存入数据库单条记录,期望改为每行对应一条学生姓名与邮箱的独立记录,示例如下:

Student Name Student email
name1 name1@gmail.com
name2 name2@gmail.com
name3 name3@ymail.com

当前代码的核心问题:前端将所有姓名、邮箱分别存入数组后转成JSON字符串提交,后端直接将整个JSON字符串作为单条记录插入,导致数据被合并成一行。以下是修改后的完整解决方案:


一、前端(Index.html)修改

调整数据收集方式,将每行学生信息封装为独立对象,组成数组后转JSON提交,确保后端能解析出每条记录:

JavaScript代码修改

$(document).ready(function() {
  var id = 1;
  // 添加行逻辑
  $("#butsend").click(function() {
    var newid = id++;
    $("#table1").append('<tr valign="top" id="' + newid + '">\n\
        <td width="100px" >' + newid + '</td>\n\
        <td width="100px" class="name' + newid + '">' + $("#name").val() + '</td>\n\
        <td width="100px" class="email' + newid + '">' + $("#email").val() + '</td>\n\
        <td width="100px"><a href="javascript:void(0);" class="remCF">Remove</a></td>\n\ </tr>');
    // 清空输入框
    $("#name").val("");
    $("#email").val("");
  });
  // 删除行逻辑
  $("#table1").on('click', '.remCF', function() {
    $(this).parent().parent().remove();
  });
  // 保存到数据库逻辑
  $("#butsave").click(function() {
    var students = [];
    // 遍历所有数据行(跳过表头)
    $("#table1 tr:not(:first)").each(function() {
      var name = $(this).find("td:nth-child(2)").text();
      var email = $(this).find("td:nth-child(3)").text();
      if(name.trim() && email.trim()){ // 过滤空行
        students.push({name: name, email: email});
      }
    });
    if(students.length === 0){
      alert("请添加学生数据");
      return;
    }
    var sendData = JSON.stringify(students);
    $.ajax({
      url: "save.jsp",
      type: "post",
      data: {students: sendData},
      success: function(data) {
        alert(data);
        // 清空表格(可选)
        $("#table1 tr:not(:first)").remove();
        id = 1;
      }
    });
  });
});

HTML结构(无需修改)

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div style="margin: auto;width: 60%;">
  <form id="form1" name="form1" method="post">
    <div class="form-group">
      <label for="email">Student Name:</label>
      <input type="text" name="sname" class="form-control" id="name">
    </div>
    <div class="form-group">
      <label for="pwd">Student email:</label>
      <input type="text" name="email" class="form-control" id="email">
    </div>
    <input type="button" name="send" class="btn btn-primary" value="add data" id="butsend">
    <input type="button" name="save" class="btn btn-primary" value="Save to database" id="butsave">
  </form>
  <table id="table1" name="table1" class="table table-bordered">
    <tbody>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>email</th>
        <th>Action</th>
      </tr>
    </tbody>
  </table>
</div>

二、后端(save.jsp)修改

接收JSON数组,解析后循环插入每条记录,同时使用PreparedStatement防止SQL注入风险:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="com.google.gson.Gson"%>
<%@page import="com.google.gson.reflect.TypeToken"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>

<%
request.setCharacterEncoding("UTF-8");
String studentsJson = request.getParameter("students");
if(studentsJson == null || studentsJson.isEmpty()){
    out.println("没有可保存的数据");
    return;
}

// 解析JSON数组为学生列表
Gson gson = new Gson();
List<Map<String, String>> students = gson.fromJson(studentsJson, new TypeToken<List<Map<String, String>>>(){}.getType());

int insertCount = 0;
try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mm_db?useUnicode=true&characterEncoding=UTF-8", "sjgf", "lkdfghd");
    // 预编译SQL,避免注入风险
    String sql = "INSERT INTO user_data(Name, email) VALUES(?, ?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    
    for(Map<String, String> stu : students){
        pstmt.setString(1, stu.get("name"));
        pstmt.setString(2, stu.get("email"));
        insertCount += pstmt.executeUpdate();
    }
    
    out.println("成功插入 " + insertCount + " 条数据!");
    // 关闭资源
    pstmt.close();
    conn.close();
}catch(Exception e){
    e.printStackTrace();
    out.println("数据插入失败:" + e.getMessage());
}
%>

注意事项

  1. 需引入Gson库(可下载jar包放入项目WEB-INF/lib目录,或通过Maven依赖管理),用于JSON解析。
  2. 请将数据库连接参数(用户名、密码、数据库名)修改为实际配置。
  3. 前端添加了清空输入框和表格的逻辑,可根据业务需求调整。

内容的提问来源于stack exchange,提问作者Liton Biswas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:48:22