Ajax,将另一张网页内容显示在主页面中

实现功能,将web1.html里的内容通过ajax显示在Demo1.jsp中,初学者可以通过web的框架来思考这个东西,不过在这个案例中,想插入的位置都是自己可以控制的,方便快捷。
在这里插入图片描述

web1.html中的代码:
在这里插入图片描述

Demo1.jsp中的代码:
在这里插入图片描述

实现:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Demo1.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript">
	window.onload =function (){		//网页加载完事件
		document.getElementsByTagName("a")[0].onclick = function(){	//获取网页中的a节点,设置单机事件
			ajax=new XMLHttpRequest();		//创建一个ajax
			var method="GET";				//创建方法和url
			var url=this.href;
			ajax.open(method, url);			//方法设置
			ajax.send();				//方法发送,可以填null也可以不填
			ajax.onreadystatechange = function(){		//ajax发送后,服务器请求变化
				if(ajax.readyState == 4){		//服务器响应4表示成功
					if(ajax.status == 200 || ajax.status == 304){		//文件加载成功
						document.getElementById("d1").innerHTML=ajax.responseText;	//获取网页中html元素并且修改期中值
					};
				};
			};
			return false;		//默认不会跳转过去
		};
	};
</script>
  </head>
  
  <body>
   <a href="sunWeb/web1.html">点击我打开子网页</a>
   <div id="d1">
   
   </div>
  </body>
</html>

效果图
点击前:
在这里插入图片描述

点击后:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43299461/article/details/85216395