Struts1.*与JQuery的json交互

2010-07-05 19:58

Struts1.*与JQuery的json交互

by

at 2010-07-05 11:58:50

original http://www.javaeye.com/topic/705749

这两天项目需要,Struts1.*框架使用JQuery的Json来异步查询信息来显示内容,写完本人总结下~~~

 

 

一、需要的东西

1. jquery的js文件:本人使用的是jquery-1.4.2.min.js.(可以自己去官网下载)

 

 

二、jsp页面写法

1. 首先在head中引入jquery的js文件:

<script type="text/javascript" src="${contextPath }/js/tips.js"></script>

 

 

2. 页面button的onclick事件:

<a href="#" onclick="f_getInfo('send.id=${send.id}')">预览</a>

 

 

3. 下面是js中jquery的代码:

function f_getInfo(param) {
    $.post("${contextPath}/send/preSendInfo.do?",param,
        function (data) {
            var obj;
            obj = eval(data);
            f_perview(obj);
         },"json");
}


function f_perview(obj) {
    var MSG1 = new CLASS_MSN_MESSAGE("aa",obj.twidth,obj.theight,obj.sname,obj.sname,"用户:"+obj.username + "<br> 消息URL:" + obj.contentUrl);
    MSG1.rect(null,null,null,screen.height-50);
    MSG1.speed = obj.keepTime; 
    MSG1.step = 8; 
    MSG1.show();
}

 

说明:第一个js的方法是jquery与后台交互,function方法是返回的结果(这里只有返回成功的消息才会执行该方法),eval是json转换成对象的函数,之后是调用下面的方法传递一个参数。下面的方法就是显示内容了。显示对象的内容使用的是:***.后台bean对象的成员变量。

 

 

4. action类中的写法:

public ActionForward preSendInfo() throws IOException {
        
        send = sendService.getSendInfo(send.getId());
        if(send == null) {
            return StrutsEnv.getActionMapping().findForward(FAILED);
        }   
        
        String result = JsonUtil.object2json(send).toString();
        
        HttpServletResponse response = StrutsEnv.getResponse();
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(result);
        pw.flush();
        
        return null;
    }

 

说明:action类中的方法中返回值应该准换成json格式,然后使用response返回到jsp页面。

         注意renturn 后面为null。

 

 

5. struts-config.xml文件的写法跟普通的写法一样,只是不用谢forward了~~~

<action attribute="send" name="send" path="/send/preSendInfo" 
            scope="request"   type="com.uucall.messagepush.struts.BeanAction">
        </action>

 

 

上面就是struts1.*与jquery的ajax交互使用json的所有方法,以后方便自己忘记之后熟悉~~~

      <br><br>
      作者: <a href="http://ipc.javaeye.com">mxl86</a> 
      <br>
      声明: 本文系JavaEye网站发布的原创文章,未经作者书面许可,严禁任何网站转载本文,否则必将追究法律责任!
      <br><br>
      <span style="color:red">
        <a href="http://www.javaeye.com/topic/705749" style="color:red">已有 <strong>0</strong> 人发表回复,猛击-&gt;&gt;<strong>这里</strong>&lt;&lt;-参与讨论</a>
      </span>
      <br><br><br>

JavaEye推荐