需求:要实现的效果是当我单击超链接时,在右侧部分进行内容的显示
1.写一个servlet(用于得到想要输出的值)
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("上证指数:3560");
out.flush();
out.close();
}
}
2.配置web.xml
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>servlet.DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/demo1.do</url-pattern>
</servlet-mapping>
3.编写index.jsp界面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function getXhr(){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function sendRequest(){
var xhr = getXhr();
xhr.open("get","demo1.do");
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
var msg = xhr.responseText;
document.getElementById("msg").innerHTML=msg;
}
};
xhr.send(null);
}
</script>
</head>
<body>
<a href="#" οnclick="sendRequest()">查看上证指数</a>
<span id="msg"></span>
<table>
<tr>
<td>新闻标题</td>
<td>时间</td>
</tr>
<tr>
<td>新加坡</td>
<td>2015-11-12</td>
</tr>
</table>
</body>
</html>
4.实现的效果
单击超链接之后: