AngularJS尝鲜——Ajax请求

AngularJS不仅仅只有双向绑定等等功能,还有发送Ajax请求的Api。

效果图:

这里写图片描述

请求的文件(data.php):

<?php
$data = [
    '股市下跌',
    '清明小长假结束',
    '我要接着学习了'
];
echo json_encode($data);

Jqurey方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用jquery加载网络数据</title>
</head>
<script src="http://cdn.bootcss.com/jquery/3.2.0/jquery.min.js"></script>
<body>
<h1>使用jquery加载网络数据</h1>
    <ul>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</body>
<script>
    $.get('data.php',function(rs){
        var i = 0;
        $('li').each(function(){
            this.innerHTML = rs[i++];
        });
    },'json');
</script>
</html>

AngularJS方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用Angular加载网络数据</title>
</head>
<script src="//cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script>
<body>
    <h1>使用Angular加载网络数据</h1>
    <ul ng-app="news" ng-controller="con">
        <li ng-repeat="n in news">{{n}}</li>    
    </ul>
</body>
<script>
    var app = angular.module('news',[]);
    app.controller('con',function($scope,$http){
        $http({
            method:'GET',
            url:'data.php',          
        }).then(function successCallback (rs){
            $scope.news = rs.data;
        });
    });
</script>
</html>

使用JQuery中的Ajax和使用AngularJS中的Ajax本质上没有区别,只是api的区别,但是获取数据之后,jquery方式必须自己写操作dom元素的代码,但是AngularJS中就不用手动写操作dom元素的代码,而只是用一个ng-repeat标签来操作dom,换句话说,AngularJS操作dom的代码已经被封装起来了,我们不用写,而jquery中必须写。

原文地址:https://www.cnblogs.com/cnsec/p/13407010.html