struts整合jQuery与ajax

首先来一个测试ajax的按钮:

<input type="button" value="ajax" id="test" onclick="testajax()">

然后为其注册ajax方法:

View Code
 1 <script type="text/javascript">
 2     
 3     function testajax() {
 4 //        var ctx = ${pageContext.request.contextPath};
 5         alert("in");
 6          $.ajax({
 7              url : '/testStruts/ajax.action',
 8              data : { 'photourl' : 'test'},
 9              type : 'POST',
10              dataType : 'html',
11              success : function(json) {
12              alert(json);
13              },
14              error : function(xhr, status) {
15                  alert('更新错误!');
16              },
17              });
18 
19     }
20     
21 </script>

struts.xml的配置:

View Code
1 <!-- 注意,result不需要配置name属性-->
2 
3 <action name="ajax" class="chj.abc.ajaxAction" method="ajax">
4             <result >
5                 /ajax.jsp
6             </result>
7  </action>

Action:

View Code
 1 package chj.abc;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 import org.apache.struts2.ServletActionContext;
10 
11 import com.opensymphony.xwork2.ActionSupport;
12 
13 
14 public class ajaxAction extends ActionSupport{
15     public String ajax() throws IOException{
16         System.out.println("testing ajax.....");
17         
18         HttpServletRequest request = ServletActionContext.getRequest();
19         HttpServletResponse response = ServletActionContext.getResponse();
20         // 设置字符集
21         response.setContentType("text/plain");// 设置输出为文字流
22         response.setCharacterEncoding("UTF-8");
23         PrintWriter out = response.getWriter();
24         String type=request.getParameter("photourl");//interval
25         System.out.println(type);
26         out.write("hello world");
27             out.flush();
28             out.close();
29 
30         return null;
31     }
32 }

注意:Action的最后返回的是null

posted on 2013-01-17 23:42  saobchj  阅读(315)  评论(0编辑  收藏  举报

导航