//前台js代码实现异步servlet请求
var xmlHttp;
//创建xmlHttp
function createXmlHttp(){
var activeKey = new Array("MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
if(window.ActiveXObject){
for(var i=0;i<activeKey.length;i++){
try{
xmlHttp = new ActiveXObject(activeKey[i]);
if(xmlHttp!=null){
return xmlHttp;
}
}catch(error){
continue;
}
}
throw new Error("客户端浏览器版本低,不支持XMLHttpRequest对象,请更新浏览器");
}else if(window.XMLHttpRequest){
xmlHttp = new window.XMLHttpRequest();
return xmlHttp;
}
}
//地址与参数拼接函数
function addUrlParameter(url,parameterName,parameterValue){
url += (url.indexOf("?"))==-1 ? "?" : "&";
url += encodeURIComponent(parameterName) + "=" + encodeURIComponent(parameterValue);
return url;
}
xmlHttp = createXmlHttp();
xmlHttp.send(null);
}
function readystatechangeHandler(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var str = xmlHttp.responseText;
var div = document.getElementById('divServeMsg');
div.innerHTML = "<b>"+str+"</b>";
}
}
var xmlHttp;
//创建xmlHttp
function createXmlHttp(){
var activeKey = new Array("MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
if(window.ActiveXObject){
for(var i=0;i<activeKey.length;i++){
try{
xmlHttp = new ActiveXObject(activeKey[i]);
if(xmlHttp!=null){
return xmlHttp;
}
}catch(error){
continue;
}
}
throw new Error("客户端浏览器版本低,不支持XMLHttpRequest对象,请更新浏览器");
}else if(window.XMLHttpRequest){
xmlHttp = new window.XMLHttpRequest();
return xmlHttp;
}
}
//地址与参数拼接函数
function addUrlParameter(url,parameterName,parameterValue){
url += (url.indexOf("?"))==-1 ? "?" : "&";
url += encodeURIComponent(parameterName) + "=" + encodeURIComponent(parameterValue);
return url;
}
//按钮触发事件
xmlHttp = createXmlHttp();
xmlHttp.onreadystatechange = readystatechangeHandler;
//红色代码实现调用servlet路径与参数拼接,同时进行传递
xmlHttp.send(null);
}
function readystatechangeHandler(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var str = xmlHttp.responseText;
var div = document.getElementById('divServeMsg');
div.innerHTML = "<b>"+str+"</b>";
}
}
}
//后台servlet参数传递函数
String cunstomerInfo = req.getParameter("customerInfo").toString();
String msg = "服务器获得你的消息,时间"+ new Date().toLocaleString()+";你的消息为" + cunstomerInfo +"中文测试<br>你的地址为"+req.getLocalAddr();
resp.setCharacterEncoding("utf-8"); //解决返回参数乱码问题,前台的jsp默认编码也应该设置为utf-8
//蓝色代码实现参数传回给页面。前台使用 xmlHttp.responseText接收
PrintWriter out = resp.getWriter();
out.write(msg);
out.close();