Ajax,將另一張網頁內容顯示在主頁面中
阿新 • • 發佈:2018-12-23
實現功能,將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>
效果圖
點選前:
點選後: