jsp页面发送Ajax请求,和html中其实一样,jsp代码如下:
<%--
Created by IntelliJ IDEA.
User: 17605
Date: 2021/6/6
Time: 19:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试页面</title>
<script type="text/javascript" src="/servlet_demo/static/js/jquery-2.1.4.min.js"></script>
</head>
<body>
欢迎来到第一个JSP页面!!!<br><br>
<a href="/servlet_demo/myServlet.do?COMMAND=ADD">点击进行添加</a><br><br>
<a href="/servlet_demo/myServlet.do?COMMAND=UPDATE&id=4">点击进行修改</a><br><br>
<a href="/servlet_demo/myServlet.do?COMMAND=DEL&id=12">点击进行删除</a><br><br>
<a href="/servlet_demo/myServlet.do?COMMAND=FIND&id=9">按照Id进行查询</a><br>
<script type="text/javascript">
$.ajax({
url: '/servlet_demo/myServlet.do?COMMAND=FINDALL',
type: 'get',
dataType: 'json',
success:function (result) {
console.log(result);
}
});
</script>
</body>
</html>
servlet中的相关代码:
private void findAll(HttpServletRequest request,HttpServletResponse response) throws IOException{
List<People> list = peopleDao.findAll();
response.setContentType("text/plain;charset=utf-8");
PrintWriter writer = response.getWriter();
if(list != null && list.size() > 0){
// 转为json串
String jsonStr = JSON.toJSONString(list);
writer.write(jsonStr);
} else {
writer.write("查无数据!");
}
}
dao层相关代码:
/*
* @description: 查询所有记录
* @param: []
* @return: java.util.List<com.ycz.domain.People>
* @author: yanchengzhi
* @date: 2021/6/14 14:43
*/
public List<People> findAll() {
List<People> peoples = new ArrayList<>();
String sql = "select id,name,FROM_UNIXTIME(birth) birthday,tag from people";
Connection connection = DataSourceManager.getConnection();
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
ps = connection.prepareStatement(sql);
resultSet = ps.executeQuery();
while(resultSet.next()){
People p = new People();
p.setId(resultSet.getInt("id"));
p.setName(resultSet.getString("name"));
p.setBirth(resultSet.getDate("birthday"));
p.setTag(resultSet.getInt("tag"));
peoples.add(p);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceManager.closeConnection(connection);
DataSourceManager.closeStatement(ps);
DataSourceManager.closeResultSet(resultSet);
}
return peoples;
}
打开浏览器控制台测试:
ajax请求及响应是没问题的。
注意一个地方,前段时间自己有点秀逗了,犯了一个低级错误,ajax请求中的这个地方:
如果这行注释掉:
再看控制台:
和刚才不一样的是:刚才打印的是转换后的json对象,而现在打印的只是json字符串,与后端返回结果无关,后端返回的一直是json串,只不过dataType属性值为json时,浏览器会自动将json串转换为json对象,如果不写dataType,那么它默认的值是text,也就是纯文本格式。省略dataType属性和下面这样写是等效的:
查看控制台打印:
没问题。怪自己太菜,以前没怎么注意。