struts2.1.6版如何使用ajax

需注意的事项
1、需引入struts2-dojo-plugin-2.1.6.jar
2、页面标签的变化如下:
ajax.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%><!-- 注意 --> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>      
    <title>Ajax Demo</title>
    <sx:head/><!-- 注意 -->
  </head>
  
  <body>&nbsp; 
<h1>Ajax Dmeo:</h1>
<div id="show">一个div</div>
<s:form namespace="/demo" action="ajax!testAjax" method="post"><!-- 注意 -->
	<s:textfield name="name"></s:textfield>
	<sx:submit value="修改上面div的值" targets="show"></sx:submit><!-- 注意 -->
</s:form>
  </body>
</html>


package cn.ibeans.demo.web.action;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;

@Namespace("/demo")
@Results({
	@Result(name="ok",location="ajaxResult.jsp")
})
public class AjaxAction extends ActionSupport {
	private static Logger log= Logger.getLogger(AjaxAction.class);
	private String data;

	public String getData() {
		return "服务器的返回值:"+data;
	}

	public void setData(String data) {
		this.data = data;
	}
	
	public String testAjax() throws Exception{
		log.info("ajax 调用成功!");
		return "ok";
	}

	@Override
	public String execute() throws Exception {
		log.info("ajax 调用成功!");
		return super.SUCCESS;
	}
	
	
}


ajaxResult.jsp:
<%@ taglib prefix="s" uri="/struts-tags" %>

<%
    request.setAttribute("decorator", "none");
    response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
    response.setHeader("Pragma","no-cache"); //HTTP 1.0
    response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
    System.out.println("ajaxResult.jsp is called");
%>

Result:  <s:property value="data"/><br/>

这样ajaxResult.jsp的内容将会出现在ajax.jsp的id="show"的div中

你可能感兴趣的:(apache,Ajax,jsp,struts,dojo)