关于作业问题
这个课程的粗略查询,我使用的是ajax异步查询,不需要提交按钮,就能显示查询的结果。
但是要对查询的内容进行分页,我这里是异步,不是通过request调转的页面,使用request.setArrtibute()设置参数,前端就无法获得,就没办法设置页数?
请问老师这个怎么解决?
5
收起
正在回答 回答被采纳积分+1
2回答
好帮手慕珊
2018-04-07 12:05:11
可以参考如下代码。如果map中还存有List,那么就在for循环中再写一个循环遍历List集合。注意此处用到了net.sf.json.JSONObject类,可以在本课程教辅区下载相关jar包或自行搜索下载。祝学习愉快!
Servlet:
package cn.java.servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Servlet implementation class MapServlet
*/
@WebServlet("/MapServlet")
public class MapServlet extends HttpServlet {
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String,String> map=new HashMap<String,String>();
map.put("001", "apple");
map.put("002", "banana");
map.put("003", "pear");
JSONObject json=JSONObject.fromObject(map);
response.getOutputStream().write(json.toString().getBytes("utf-8"));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>map demo</title>
<script type="text/javascript"
src="<%=basePath%>/resources/js/jquery-1.4.2.js"></script>
</head>
<body>
<center>
<input type="submit" value="查询" id="search">
<table width="800px" cellspacing="0px" cellpadding="0px" border="1px">
<thead>
<tr>
<th>key</th>
<th>value</th>
</tr>
</thead>
<tbody id="cont">
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</center>
</body>
<script type="text/javascript" >
$("#search").click(function(){
//单击查询按钮的时候触发ajax事件
$.ajax({
url:"<%=basePath%>/MapServlet",
type:"post",
data:{},
dataType:"json",
success:function(json){
var s = null;
for(var key in json) {
s = s+ "<tr><td>" + key +"</td><td>"+ json[key] + "</td></tr>";
$("#cont>tr").remove();
}
$("#cont").html(s);
}
});
});
</script>
</html>
Java Web基础入门2018版
- 参与学习 716 人
- 提交作业 185 份
- 解答问题 1363 个
会Java?懂前端基础?想学后台开发?那么,赶快来学习《Java Web入门》路径吧。本路径主要介绍Java Web的基础知识,并配有大量案例,定会让你收获多多!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星