也为简单的业务需要,所以使用了Struts配合JQuery制作的一个简单的AJAX的例子,希望有兴趣的朋友可以看看。
- <script type="text/javascript">
- <!--
- //注:每个嵌入页必须定义该方法,供父窗口调用,并且返回true或false来告之父窗口是否关闭
- function Ok(){
- clickButton();
- }
- function clickButton()
- {
- var url = 'ajaxRequest.action';
- var params = {
- name:$('#name').attr('value')
- };
- jQuery.post(url, params, callbackFun, 'json');
- }
- function callbackFun(data)
- {
- if(data.result=="success"){
- //获取数据后渲染页面
- alert(data.result);//对应HelloWorld类的message属性
- window.parent.JqueryDialog.SubmitCompleted(null, true, true);
- }else{
- $('#nameerror').attr('value',data.result);
- }
- }
- </SCRIPT>
- <body>
- <input name="username" type="text" id="name"/><input type="text" id="nameerror"></label>
- <br />
- <input name="password" type="password">
- <br />
- <input type="button" value="ok">
- This is my JSP page. 你好
- <br>
- </body>
上述是弹出框的页面代码
一下是引导页面
- <html>
- <head>
- <base href="<%=basePath%>">
- <link type="text/css" rel="stylesheet" href="css/jquery_dialog.css" />
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- --><script type="text/javascript" src="js/jquery_dialog.js"></script>
- <SCRIPT type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
- </head>
- <body>
- <input id="name" type="text">
- <input type="button" value="ok" onclick="JqueryDialog.Open('编辑', 'hello.action', 350, 160);">
- </body>
- </html>
一下为action
- public class HelloWorld extends ActionSupport {
- /**
- *
- */
- private static final long serialVersionUID = 7897303483903148263L;
- private String name;
- private String result;
- // ajax请求参数赋值
- public void setName(String name) {
- this.name = name;
- }
- // ajax返回结果
- public String getResult() {
- return result;
- }
- public String execute() {
- this.result = "success"+name;
- return "success";
- }
- }
触发也面代码
- package test;
- import com.opensymphony.xwork2.ActionSupport;
- public class HelloAction extends ActionSupport {
- /**
- *
- */
- private static final long serialVersionUID = 3035672864398320366L;
- @Override
- public String execute() throws Exception {
- // TODO Auto-generated method stub
- System.out.println("hahahahhaha");
- return "success";
- }
- }
一下是struts.xml配置文件
这里需要引入struts2-json-plugin.jar包 很囧的一点是我悲剧的在action中写了方法返回值为void,居然神奇的调用执行了,就因为这个我调试了N久,一直觉得奇怪,怎么就没有返回值呢?
- <struts>
- <package name="ajax" extends="json-default">
- <action name="ajaxRequest" class="test.HelloWorld">
- <result type="json"></result>
- </action>
- <action name="hello" class="test.HelloAction">
- <result name="success">hello.jsp</result>
- </action>
- </package>
- </struts>
本文转自yunlielai51CTO博客,原文链接:http://blog.51cto.com/4925054/1148419,如需转载请自行联系原作者