在angularJS中與遠程HTTP服務器交互時會用一個非常關鍵的服務-$http。
下面進行$http服務的使用說明,調用如下:
1.config為一個JSON對象,其中主要包含該請求的url、data、method等,如{url:"login.do",method:"post",data:{name:"12346",pwd:"123"}}。
2、success為請求成功后的回調函數,error為請求失敗后的回調函數,這里主要是對返回的四個參數進行說明。
為了方便大家與HTTP服務器進行交互,angularJS提供了各個請求方式下方法。
$http.put/post(url,data,config) url、name必填,config可選
$http.get/delete/jsonp/head(url,confid) url必填,config可選
url、data、config與$http的參數一致,
下面有一個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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答