如何使用AJAX从Servlet中获取多个值(JSP场景)
解决方案:用JSON传递多值结构化数据
你现在的问题核心是Servlet直接拼接输出两个字符串,AJAX拿到的是混在一起的内容,没法区分哪个是firstname哪个是telephone。最靠谱的解决方式是用JSON格式传递数据,它能把多个字段封装成结构化的键值对,前端可以轻松解析每个值。
步骤1:修改Servlet,返回JSON格式响应
首先要调整Servlet的输出逻辑,把查询到的两个值打包成JSON对象,同时设置响应的Content-Type为application/json,告诉前端这是JSON数据。另外注意你的SQL里有个拼写错误:fistname应该是firstname,这个得修正,不然会查不到数据哦。
修改后的Servlet代码:
public class GetCustomerDetails extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应类型为JSON,编码为UTF-8避免乱码 response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); int customerId = Integer.valueOf(request.getParameter("customerId")); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", ""); // 修正SQL中的拼写错误:fistname → firstname PreparedStatement ps = con.prepareStatement("SELECT firstname, telephone FROM customers WHERE customerid=?"); ps.setInt(1, customerId); ResultSet result = ps.executeQuery(); if (result.next()) { // 构建JSON字符串,把两个字段打包成键值对 String jsonStr = String.format("{\"firstname\":\"%s\", \"telephone\":\"%s\"}", result.getString("firstname"), result.getString("telephone")); out.print(jsonStr); } else { // 没有找到数据时返回空值的JSON对象 out.print("{\"firstname\":\"\", \"telephone\":\"\"}"); } // 记得关闭数据库资源(实际项目中建议用try-with-resources自动关闭) result.close(); ps.close(); con.close(); } catch (ClassNotFoundException ex) { Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex); out.print("{\"error\":\"数据库驱动加载失败\"}"); } catch (SQLException ex) { Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex); out.print("{\"error\":\"数据库查询错误\"}"); } finally { out.close(); } } @Override public String getServletInfo() { return "Short description"; } }
步骤2:修改AJAX代码,解析JSON数据
在jQuery的AJAX请求里,添加dataType: 'json'参数,这样jQuery会自动把返回的JSON字符串解析成JavaScript对象,你就能直接通过.访问对应的字段了。
修改后的AJAX代码:
<script> function getCustomerDetailsAjax(str) { str = $('#customerId').val(); if (document.getElementById('customerId').value <= 0) { document.getElementById('firstName').value = " "; document.getElementById('telephone').value = " "; document.getElementById('vehicleMake').value = " "; document.getElementById('vehicleModel').value = " "; document.getElementById('vehicleColor').value = " "; } else { $.ajax({ url: "GetCustomerDetails", type: 'POST', data: {customerId: str}, dataType: 'json', // 指定返回数据类型为JSON success: function (data) { // 直接访问JSON对象里的字段,弹出提示 alert(`First Name: ${data.firstname}\nTelephone: ${data.telephone}`); // 也可以把值直接填充到页面输入框里 document.getElementById('firstName').value = data.firstname; document.getElementById('telephone').value = data.telephone; }, error: function(xhr, status, error) { // 处理请求失败的情况 alert(`请求出错:${error}`); } }); } } </script>
为什么推荐用JSON?
- 结构化清晰:每个字段都有明确的键名,不会像拼接字符串那样因为特殊字符(比如名字含空格、电话含横杠)导致解析出错。
- 扩展性强:以后要添加更多字段(比如你代码里的车辆相关信息),只需要在JSON里新增键值对,前端代码改动极小。
内容的提问来源于stack exchange,提问作者Jananath Banuka
相关产品推荐
相关产品推荐

