现在的位置: 首页 > 综合 > 正文

struts2用ajax返回一个jsonArray

2018年04月30日 ⁄ 综合 ⁄ 共 1723字 ⁄ 字号 评论关闭

 用ajax接受一个list,list在action中转为json数组,ajax在页面接收一个json数组,以下使用JSON-lib包,JSON-lib包同时依赖于以下的JAR包:(同时也使用struts-json-plugin.jar

     1.commons-lang.jar

     2.commons-beanutils.jar

      3.commons-collections.jar

      4.commons-logging.jar 

      5.ezmorph.jar

      6.json-lib-2.2.2-jdk15.jar

 

 

一,在action中

@Controller

public
class
OperateEmp extends ActionSupport {

    @Resource

    private EmpServiceempService;

 

    private
JsonArray
jsonArrary;
//jsonArray的形式返回

 

    public String delEmp() {

        //这是我service层的方法,得到一个emp集合

        List<Emp> empsList = empService.getAllEmps();

 

/* 如果在要把list转为json数组的集合中,存在外键的话,会进入死循环(Thereis
a cycle in the * hierarchy!
),那么需要忽略掉外键列,如本例中的emp对象中的dep

*/      

        JsonConfig config = new JsonConfig();

        config.setIgnoreDefaultExcludes(false);//设置不忽略默认的不包括字段

        config.setExcludes(new String[]{"dep"});//这里是设置哪些字段不包括在内,这里把外键dep设置,实际中有很多属性都是不需要的,那么就可以设置在其中

 

        JSONArray arrary = new JSONArray();

        arrary = JSONArray.fromObject(empsList,config); //使用配置config

        jsonArrary = arrary.toString();

        returnSUCCESS;
//这里要是SUCCESS

    }

 

    public JsonArray getJsonArrary() {

        returnjsonArrary;

    }

 

    public
void
setJsonArrary(JsonArray jsonArrary) {

        this.jsonArrary = jsonArrary;

    }

 

}

 

二 配置文件:

<packagename="operateEmp"namespace="/operateEmp"extends="json-default">

        <actionname="empAction"class="operateEmp"method="delEmp">

            <resulttype="json">

                <paramname="root">jsonArrary</param>

            </result><!--
无需视图配置 -->

        </action>

    </package>

 

 

三,页面

<scripttype="text/javascript">

    function delEmp(empId){

      $.post("${pageContext.request.contextPath}/operateEmp/operate_delEmp.do",{'empId':empId},function(data){

        $.each(data,function(){

            alert(this.empId);

            });

        });

    }

</script>

抱歉!评论已关闭.