前端代码:
<html>
<head>
<meta charset="UTF-8">
<title>异步请求</title>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">//利用jquery实现ajax使用
$(document).ready(function(){$("#btn").click(function(){$.post("${pageContext.request.contextPath}/ajaxServlet?time="+new Date().getTime(),function(data,status){alert("数据:" + data + "\n状态:" + status);$("#text").val(data);});});});
</script>
</head>
<body>
点击进行异步请求:<input type="button" value="异步请求" name="btn" id="btn" /><input type="text" id="text" value="唐老鸭"/>
<!-- <div id="text"></div> -->
</body>
</html>
后台代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubSystem.out.println(request.getParameter("time"));String url=request.getServletContext().getRealPath("demo.txt");File file= new File(url);//创建输入流FileInputStream in =new FileInputStream(file);ServletOutputStream out =response.getOutputStream();int len=0; byte[] bs= new byte[1024];while((len=in.read(bs))>0) {out.write(bs, 0, len);}}
目录结构: