1. JavaScript
function ajaxRequest(url){
var xmlHttpReq;
var response;
try{
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
try{
xmlHttpReq = new XMLHttpRequest();
}catch(e){}
}
}
try{
xmlHttpReq.open("POST", url, false);
xmlHttpReq.onreadystatechange =
function(){
if(xmlHttpReq.readyState == 4){
if(xmlHttpReq.status == 200){
response = xmlHttpReq.responseText;
}else{
alert("Problem: " + xmlHttpReq.statustext);
}
}
};
xmlHttpReq.send(null);
if(response==null){
response = xmlHttpReq.responseText;
}
}catch(e){}
return response;
}
2.JSP调用
var ajaxurl="<%=request.getContextPath()%>/adminDownload/doAjaxTest.action?";
alert(ajaxRequest(ajaxurl));
3.struts.xml配置
<action name="doAjaxTest" class="cots.admin.action.COTSDownloadReportAction" method="doAjaxTest"> </action>
4.Action代码
public void doAjaxTest(){
try{
HttpServletResponse res = ServletActionContext.getResponse();
PrintWriter out = res.getWriter();
out.println("get from ajax!");
}catch (Exception e) {
log.error( e.getMessage(), e);
}
}
本文介绍了一个使用JavaScript的AJAX函数发起异步请求到服务器端的Struts Action的示例。客户端通过AJAX获取服务器响应并显示结果。服务器端采用Struts框架处理请求并返回字符串响应。
1299

被折叠的 条评论
为什么被折叠?



