简单的使用AngularJS的解析JSON

    使用AngularJS+Struts2进行前后台的数据交互与显示。

  struts.xml

    配置文件需要将设置extends="json-default"  type="json"

 <package name="default" namespace="/" extends="json-default">

        <action name="ajax" class="com.Yiran583.action.ajacAction">

            <result type="json"/>

        </action>

 </package>

 

  后台代码:

    将需要作为JSON数据传递给前台的属性设置相应的getter/setter方法

    private List<Person> list = new ArrayList<Person>();

    private Person person;



    @Override

    public String execute() throws Exception {

        // TODO Auto-generated method stub



        Person person = new Person("Yiran", 20);

        Person person1 = new Person("Jiao", 22);

        Person person2 = new Person("Zhangsan", 18);



        list.add(person1);

        list.add(person2);



        list = JSONArray.fromObject(list);



        return SUCCESS;

    }



    public List<Person> getList() {

        return list;

    }



    public void setList(List<Person> list) {

        this.list = list;

    }

  前台:

    ng-repeat 循环显示 

    x.name,x.age 分别是JSON对象中的属性

    $scope.name = a.list; 将list对象返回的结果绑定到name上

<body ng-app>

    <span id="btn" style="cursor: pointer; font-size: 20px">action</span>

    <div id="rdiv" ng-controller="myCC">

        要显示数据的区域

        <li ng-repeat="x in names">

            {{x.name+" "+x.age}}

        </li>

    </div>



    <script type="text/javascript">

        function myCC($scope, $http) {

            var url = "ajax.action";

            $http.get(url).success(function(a) {

                $scope.names = a.list;

            });

        }

    </script>

</body>

  

 

你可能感兴趣的:(AngularJS)