JavaScript实现AJAx的使用

工程目录结构:
在这里插入图片描述
代码:serlvet代码:

@WebServlet("/ajaxServlet")
public class ajaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//得到目标文件路径
		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);
		}
		
	}
jsp页面:


<html>
<head>
<meta charset="UTF-8">
<title>异步请求</title>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
function loadXMLDoc(){
	alert("方法运行")
	var xmlhttp;
	//实例化XMLHTTPRequest对象
	if(window.XMLHttpRequest){
		//针对ie7+、firefox、chrome等浏览器
		xmlhttp=new XMLHttpRequest();
	}
	else{
		//针对ie5、6
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	xmlhttp.onreadystatechange=function(){
		//readystate状态为4(服务器请求完成)并且http的状态码为200(成功)时
		if(xmlhttp.readyState==4 && xmlhttp.status==200){
			alert(xmlhttp.responseText)
			document.getElementById("text").value=xmlhttp.responseText;
		}
	}
	
xmlhttp.open("GET",
			"${pageContext.request.contextPath}/ajaxServlet?name="
			+ window.encodeURIComponent("嘻嘻", "utf-8")
			+ "&time=" + new Date().getTime());
	xmlhttp.send();
}


</script>
</head>
<body>
点击进行异步请求:<input type="button" value="异步请求" name="btn" id="btn" onclick="loadXMLDoc()"/>
<input type="text" id="text"/>
</body>
</html>

结果图:在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42952331/article/details/84825127