基本語法:
$http.post('url',{},{}).success(function(data,status,headers,config){ }).error(function(data,status,headers,config){ })
$http.post接受三個引數:
1. url: 請求的路徑
2. 請求傳送的資料: json物件 {name:'code_bunny'}
3. 請求配置的引數: json物件 {params: {id:5}} 這樣得到的實際路徑就是url?id=5
$http.post返回的物件有兩個回撥方法:
1. success: 請求成功的回撥
2. error: 請求失敗的回撥
這兩個方法都有四個引數:
①data: 返回的資料(或錯誤)
②status: 響應的狀態碼
③headers: 這樣一個函式,具體是什麼暫時不詳
function (name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }
④congfig: 請求的配置物件
{ method: "GET", url: "/api/user",
params: {id:5}
}
下面看例項:
將請求的資料物件的name屬性的值再返回,放入span標籤中
html:
<!DOCTYPE html> <html ng-app = 'HttpGet'> <head> <title>18.2 $http.post方法</title> <meta charset="utf-8"> <script src="angular.js"></script> <script src="script.js"></script> </head> <body> <div ng-controller = "dataController"> <span>{{data}}</span> </div> </body> </html>
js:
var httpGet = angular.module('HttpGet',[]); httpGet.factory('getData',function($http,$q){ return function(){ var defer = $q.defer(); $http.post('/api/user',{name:'code_bunny'}).success(function(data,status,headers,congfig){ defer.resolve(data); }).error(function(data,status,headers,congfig){ defer.reject(data); }); return defer.promise } }); httpGet.controller('dataController',function($scope,getData){ $scope.data = getData() });
後端node程式碼:
var express = require('express'); var app = express(); app.use(express.bodyParser()); app.use(express.static(__dirname+'')); app.post('/api/user',function(req,res){ res.send(req.body.name) }); app.listen(3000);
完成程式碼地址:https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/18.2%20%24http.post