angularjs速成学习个人理解_5$http服务

来源:互联网 发布:开发上位机界面软件 编辑:程序博客网 时间:2024/05/22 02:15

$http是一个angularjs服务,angularjs内置了很多服务方便我们开发。如果学过jquery的$.ajax函数就很好理解$http服务。

1)$http 是一个angularjs服务,用于从远程服务中读取数据

2)这个$http服务制作一个请求发送到服务器,并且返回一个响应。
3)$http提供了几个简单的方法:
* .delete(): 用于发送delete请求)
* .get(): 用于发送get请求
* .head() 用于发送head请求
* .jsonp() 用于发送jsonp请求
* .patch() 这个不是很清楚
* .post()用于发送post请求
* .put()用于发送put请求
响应回来我们可以获取一个对象。这个对象有如下属性。
.config  用于生成请求的对象。
.data    一个字符串或一个对象,它从服务器中执行响应。
.headers 用于获取头信息的函数。
.status  一个定义HTTP状态的数字。
.statusText 定义HTTP状态的字符串。
就是简单的封装了$http服务,常规项目开发时,使用较多的是原始的内置服务$http的$http({}).then(fn1, fn2)函数进行异步数据处理。fn1成功时回调函数。fn2失败时回调函数。参数为响应回来对象.

在服务器制作一个json文件,内容为json数据数组。如下:

[{"id":"1", "num":23, "name":"James", "position":"PF", "team":"骑士", "thumb":"james.png", "votes":1988},{"id":"2", "num":30, "name":"Curry", "position":"SG", "team":"勇士", "thumb":"curry.png", "votes":1865}]

请求如下:http://localhost:63342/angulartest/data/players_data1.json



======>

通过$http发送get请求如下代码:

$http({method: "GET",url: "http://localhost:63342/angulartest/data/players_data1.json"}).then(function(resp) {$scope.respData = resp.data;}, function(resp) {$scope.respData = resp.statusText;});

成功时,在页面中显示数据用{{respData}}。成功时显示数据,失败时显示响应状态文字。

完整代码如下:

<!DOCTYPE html><html ng-app="myApp"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><title>$http - AngularJS Test</title><style type="text/css">.test-div {margin:15px;padding:15px;border:1px solid #ccc;}</style></head><body><div class="test-div" ng-controller="myCtrl">{{respData}}</div><script type="text/javascript" src="static/js/angular-1.5.8.js"></script><script type="text/javascript">var myApp = angular.module("myApp", []);myApp.controller("myCtrl", function($scope, $http) {$http({method: "GET",url: "http://localhost:63342/angulartest/data/players_data1.json"}).then(function(resp) {$scope.respData = resp.data;}, function(resp) {$scope.respData = resp.statusText;});});</script></body></html> 

有了这部分功能后期我们的前端数据皆可以通过json数据进行获取。





原创粉丝点击