angularJS之$http:與服務(wù)器交互示例
在angularJS中與遠程HTTP服務(wù)器交互時會用一個非常關(guān)鍵的服務(wù)-$http。
- $http是angular中的一個核心服務(wù),利用瀏覽器的xmlhttprequest或者via JSONP對象與遠程HTTP服務(wù)器進行交互。
- $http的使用方式和jquery提供的$.ajax操作比較相同,均支持多種method的請求,get、post、put、delete等。
- $http的各種方式的請求更趨近于rest風(fēng)格。
- 在controller中可通過與$scope同樣的方式獲取$http對象,e.g. function controller($scope,$http){}
下面進行$http服務(wù)的使用說明,調(diào)用如下:
$http(config).success(function(data,status,headers,config){}).error(function(data,status,headers,config){});
1.config為一個JSON對象,其中主要包含該請求的url、data、method等,如{url:"login.do",method:"post",data:{name:"12346",pwd:"123"}}。
- method {String} 請求方式e.g. "GET"."POST"
- url {String} 請求的URL地址
- params {key,value} 請求參數(shù),將在URL上被拼接成?key=value
- data {key,value} 數(shù)據(jù),將被放入請求內(nèi)發(fā)送至服務(wù)器
- cache {boolean} 若為true,在http GET請求時采用默認的$http cache,否則使用$cacheFactory的實例
- timeout {number} 設(shè)置超時時間
2、success為請求成功后的回調(diào)函數(shù),error為請求失敗后的回調(diào)函數(shù),這里主要是對返回的四個參數(shù)進行說明。
- data 響應(yīng)體
- status 相應(yīng)的狀態(tài)值
- headers 獲取getter的函數(shù)
- config 請求中的config對象,同上第1點
為了方便大家與HTTP服務(wù)器進行交互,angularJS提供了各個請求方式下方法。
$http.put/post(url,data,config) url、name必填,config可選
$http.get/delete/jsonp/head(url,confid) url必填,config可選
url、data、config與$http的參數(shù)一致,
下面有一個simple demo用于展示如何使用$http()及$http.post()。
<!DOCTYPE HTML> <html lang="zh-cn" > <head> <meta charset="UTF-8"> <title>CSSClasses</title> <script src="angular.min.js" type="text/javascript"></script> <script type="text/javascript"> function ctrl($http,$scope){ $scope.login = function(user){ $http.post("login.do",user).success(function(data, status, headers, config){ alert("success"); }).error(function(data, status, headers, config){ alert("error"); }) } $scope.login1 = function(user){ $http({url:"login.do",data:user}).success(function(data, status, headers, config){ alert("success"); }).error(function(data, status, headers, config){ alert("error"); }) } } </script> </head> <body ng-app> <div ng-controller="ctrl"> <form name="loginFm"> Name:<input ng-model="user.name" /> pwd: <input ng-model="user.pwd" /> <input type="button" value="login" ng-click="login(user)" /> <input type="button" value="login1" ng-click="login1(user)" /> </form> </div> </body> </html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
angular中的http攔截器Interceptors的實現(xiàn)
本篇文章主要介紹了angular中的http攔截器Interceptors的實現(xiàn)的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02淺談angular4 ng-content 中隱藏的內(nèi)容
本篇文章主要介紹了淺談angular4 ng-content 中隱藏的內(nèi)容,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08AngularJS ng-bind-template 指令詳解
本文注意介紹AngularJS ng-bind-template 指令,這里把相關(guān)資料整理了一下,并附實例代碼,有需要的小伙伴可以參考下2016-07-07AngularJS基礎(chǔ) ng-list 指令詳解及示例代碼
本文主要介紹AngularJS ng-list 指令,這里幫大家整理了ng-list指令的基本資料,并附有示例代碼,有需要的小伙伴可以參考下2016-08-08淺談Angularjs中不同類型的雙向數(shù)據(jù)綁定
這篇文章主要介紹了淺談Angularjs中不同類型的雙向數(shù)據(jù)綁定,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07