angular能用ajax吗,在AngularJS中使用AJAX的方法

这篇博客介绍了如何在AngularJS中利用$http服务从服务器读取JSON格式的数据。通过示例代码展示了如何定义一个studentController,从data.txt文件获取学生记录,并将数据绑定到$scope上的students属性,以便在HTML表格中展示。为了运行示例,需要将textAngularJS.html和data.txt部署到服务器并访问网页。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AngularJS提供$http控制,可以作为一项服务从服务器读取数据。服务器可以使一个数据库调用来获取记录。 AngularJS需要JSON格式的数据。一旦数据准备好,$http可以用以下面的方式从服务器得到数据。

function studentController($scope,$http) {

var url="data.txt";

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

$scope.students = response;

});

}

在这里,data.txt中包含的学生记录。 $http服务使Ajax调用和设置针对其学生的属性。 “学生”模型可以用来用来绘制 HTML 表格。

例子data.txt

[

{

"Name" : "Mahesh Parashar",

"RollNo" : 101,

"Percentage" : "80%"

},

{

"Name" : "Dinkar Kad",

"RollNo" : 201,

"Percentage" : "70%"

},

{

"Name" : "Robert",

"RollNo" : 191,

"Percentage" : "75%"

},

{

"Name" : "Julian Joe",

"RollNo" : 111,

"Percentage" : "77%"

}

]

testAngularJS.html

Angular JS Includes

table, th , td {

border: 1px solid grey;

border-collapse: collapse;

padding: 5px;

}

table tr:nth-child(odd) {

background-color: #f2f2f2;

}

table tr:nth-child(even) {

background-color: #ffffff;

}

AngularJS Sample Application

NameRoll NoPercentage
{{ student.Name }}{{ student.RollNo }}{{ student.Percentage }}

function studentController($scope,$http) {

var url="data.txt";

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

$scope.students = response;

});

}

输出

要运行这个例子,需要部署textAngularJS.html,data.txt到一个网络服务器。使用URL在Web浏览器中打开textAngularJS.html请求服务器。看到结果如下:

ba5ae6bc2176a597983c4c2f2b54e9d2.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值