这是我的ajax请求
var id = $(this).attr('data-id');
$.ajax({
type: 'POST',
url: '../include/residents.jsp',
dataType: "json",
data: {
id: id,
},
success: function(data) {},
error: function(data) {}
}).done(function() {
});
这就是resident.jsp
<%@ page import="java.io.*,java.util.*, javax.servlet.*,java.text.*" %>
<%@ page import="javax.swing.*" %>
<%@page import="java.text.DateFormat"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.sql.PreparedStatement"%>
<%@ page language="java"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@ include file="dbconfig.jsp" %>
<%
String id = request.getParameter("id");
try {
conn.setAutoCommit(false);
PreparedStatement preparedStatement = null;
Map map = new HashMap();
String add_supplemental = "SELECT * FROM residence_tb WHERE ri_id = ?";
preparedStatement = conn.prepareStatement(add_supplemental);
preparedStatement.setString(1,id);
out.println("before");
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
String lname = rs.getString("ri_lname");
String fname = rs.getString("ri_fname");
String mname = rs.getString("ri_mname");
String suffix = rs.getString("ri_suffix");
String bdate = rs.getString("ri_bdate");
String age = rs.getString("ri_age");
String gender = rs.getString("ri_gender");
String status = rs.getString("ri_status");
String mobileno = rs.getString("ri_mobileno");
String telephoneno = rs.getString("ri_telephoneno");
String province = rs.getString("ri_province");
String municipality = rs.getString("ri_municipality");
String brgy = rs.getString("ri_brgy");
String street = rs.getString("ri_street");
map.put("lname", lname);
map.put("fname", fname);
}
out.println(map);
// rst.close();
// stmt.close();
conn.commit();
conn.close();
} catch(Exception e) {
e.getMessage();
e.printStackTrace();
}
%>
当我out.println(map);
得到
{fname=Juan, lname=Dela Cruz}
在回复中。当我尝试return map
时,我得到了
不兼容类型:意外返回值
如何返回map
以便我可以成功使用它或在ajax中完成功能
答案 0 :(得分:0)
请从响应中返回一个JSON字符串。 JSON是浏览器中的地图。
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put( "Status", "Success" );
jsonMap.put( "Rows", 100 );
ObjectMapper mapper = new ObjectMapper();
mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
String jsonStr = mapper.writeValueAsString( jsonMap );
response.getOutputStream().print( jsonStr );
ObjectMapper是Jackson / fastxml的一个类。此代码将JSON返回给浏览器。
response.getOutputStream().print("{\"result\":[{ \"lname\": \"Smith\", \"fname\": \"John\"}, { \"lname\": \"Smith1\", \"fname\": \"John1\" }, { \"lname\": \"Smith2\", \"fname\": \"John2\" }]}");
在浏览器中:
var res = JSON.parse(request.responseText)
console.log(res.result);