日期:2014-05-16  浏览次数:20781 次

Struts2 Ajax 示例

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);
        }
	}

?