使用JQuery.js & JQuery.form.js 插件完成对StrutsAction的异步请求,返回JSON数据

来源:互联网 发布:怎么在ubuntu上安装qq 编辑:程序博客网 时间:2024/05/16 19:20

先说哈自己遇到的相当纠结的问题: 

1. 本来使用jquery插件里面的$.getJSON 可以请求得到Action的数据,但是当传递参数给Action的时候,也得到了JSON的数据对象,但愣是不执行回调函数解析JSON数据,搞了一天也没搞好!

2. 后来使用$('#formID').submit(

function() {

$.ajax({

url: ........

.....

})

}

)遇到的是同样的问题,可以传进参数,可以得到Action返回的数据但愣是不执行jquery中的回调函数!

3. 最后改用jquery.form.js 插件测试程序,测试通过,下面将整合到自己的小项目里面!


步骤: 


1. 引入jquery.js&jquery.form.js 插件,版本很重要,两个插件必须相配,具体使用FireBug调试


2. JQuery请求代码:(参考的是jquery form plugin 文档)

<script type="text/javascript">function loadInfo() { var options = {        // target:        '#info',   // target element(s) to be updated with server response         beforeSubmit:  showRequest,  // pre-submit callback         success:       showData, // post-submit callback          // other available options:         url:       'hello.action',         // override for form's 'action' attribute         //type:      type        // 'get' or 'post', override for form's 'method' attribute         dataType:  'json'        // 'xml', 'script', or 'json' (expected server response type)         //clearForm: true        // clear all form fields after successful submit         //resetForm: true        // reset the form after successful submit          // $.ajax options can be used here too, for example:         //timeout:   3000     };      // bind form using 'ajaxForm'     $('#searchForm').ajaxForm(options); }// pre-submit callback function showRequest(formData, jqForm, options) {     // formData is an array; here we use $.param to convert it to a string to display it     // but the form plugin does this for you automatically when it submits the data     var queryString = $.param(formData);      // jqForm is a jQuery object encapsulating the form element.  To access the     // DOM element for the form do this:     // var formElement = jqForm[0];     alert('About to submit: \n\n' + queryString);      // here we could return false to prevent the form from being submitted;     // returning anything other than false will allow the form submit to continue     return true; } function showData(data) {        $("#info").html("test");//清空info内容        $.each(data.comments, function(i, item) {            $("#info").append(                    "<div>" + item.id + "</div>" +                     "<div>" + item.name + "</div>" +                    "<div>" + item.content + "</div><hr/>");        });    }// post-submit callback function showResponse(responseText, statusText, xhr, $form)  {     // for normal html responses, the first argument to the success callback     // is the XMLHttpRequest object's responseText property      // if the ajaxForm method was passed an Options Object with the dataType     // property set to 'xml' then the first argument to the success callback     // is the XMLHttpRequest object's responseXML property      // if the ajaxForm method was passed an Options Object with the dataType     // property set to 'json' then the first argument to the success callback     // is the json data object returned by the server      alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +         '\n\nThe output div should have already been updated with the responseText.'); } </script>



3. 配置Action (将不需要封装成JSON对象的 加注释: @JSON(serialize=falise), 需要引入三个jar包     1. json-core.jar 2. struts-json-plugin.jar 3. struts-junit-plugin.jar 现在还不知道最后那个包是干嘛使的?是不是没用哦)

也贴下我的Action代码吧,测试用的!

package com.sure.action;import java.util.ArrayList;import java.util.List;import com.opensymphony.xwork2.ActionSupport;import com.sure.model.Comment;public class InfoAction extends ActionSupport {private List<Comment> comments = new ArrayList<Comment>();private String keywords;public String getKeywords() {return keywords;}public void setKeywords(String keywords) {this.keywords = keywords;}public List<Comment> getComments() {return comments;}public void setComments(List<Comment> comments) {this.comments = comments;}@Overridepublic String execute() throws Exception {System.out.println("keyword: "+this.keywords);loadComments();return SUCCESS;}/** * 加载留言信息 */private void loadComments() {Comment com = new Comment();com.setId(1);com.setName("木头人");com.setContent("123 木头人");comments.add(com);com.setId(2);com.setName("不动");com.setContent("123 不动不动");comments.add(com);}}
  4. struts.xml的配置文件的内容: 

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts>    <constant name="struts.enable.DynamicMethodInvocation" value="false" />    <constant name="struts.devMode" value="true" />    <package name="default" namespace="/" extends="json-default">        <action name="hello" class="com.sure.action.InfoAction">            <result type="json">index.jsp</result>        </action>    </package><!--     <include file="example.xml"/> --></struts>