Ajax实例

HelloWorld.jsp

<%@ page contentType="text/html;charset=utf-8" language="java" errorPage="" %>
<html>
<head>
<meta http-equiv="pragma"content="no-cache">
<meta http-equiv="cache-control"content="no-cache,must-revalidate">
<meta http-equiv="expires"content="0">


<title>Ajax</title>
<script type="text/javascript">
function ok(){
var xmlhttp;
if(window.XMLHttpRequest){
//非IE
xmlhttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
}
}
xmlhttp.onreadystatechange=function(){
if(4==xmlhttp.readystate){
if(200==xmlhttp.status){
//获取返回值
var msgWelcome=xmlhttp.responseText;
var msg = document.getElementById("msg");
msg.innerHTML=msgWelcome;
}
}
}
//设定请求
xmlhttp.open("get","http://localhost:8080/Ajax/HelloWorld.do",true);
//设定http头
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
xmlhttp.send(null);
}
</script>
</head>
<body>
<span id="msg"></span>
<br>
<input type="button" onclick="ok();" value="单击此按钮" />
</body>
</html>


HelloWorld.java

package com.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 463701915463621765L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=utf-8");
//无缓存
response.addHeader("pragma", "no-cache");
response.addHeader("cache-control", "no-cache,must-revalidate");
response.addHeader("expires", "0");

PrintWriter out=response.getWriter();
out.write("当前的系统时间是:"+getCurrentDateAndTime()+"欢迎(HelloWorld)");
}

private String getCurrentDateAndTime() {
// TODO Auto-generated method stub
String currentDate="";
//设定时间格式
SimpleDateFormat format=new SimpleDateFormat("yyyy'-'MM'-'dd HH:mm:ss");
format.setLenient(false);
currentDate=format.format(new Date());
//返回当前日期
return currentDate;
}

}


[i][b]很简单的一个实例,大家用的时候要注意的是:
记得关闭缓存[/b][/i]

response.addHeader("pragma", "no-cache");
response.addHeader("cache-control", "no-cache,must-revalidate");
response.addHeader("expires", "0");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值