基本介绍
$http用于向服务端发起异步请求,同时还支持多种快捷方式如$http.get()、$http.post()、$http.jsonp。
基本使用
传递的数据可以是‘key=val&key=val‘形式,这种形式叫formData,在请求头设置成 ‘Content-Type‘: ‘application/x-www-form-urlencoded‘ ,那么只有采用这样的方式进行传递
<!DOCTYPE html><html lang="en" ng-app="App"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body><ul ng-controller="DemoController"></ul><script src="../libs/angular.min.js"></script><script> ???var App = angular.module(‘App‘, []); ???App.controller(‘DemoController‘, [‘$scope‘, ‘$http‘, function ($scope, $http) { ???????$http({ ???????????url: ‘01.php‘, ???????????method: ‘post‘, ???????????headers: { ???????????????‘Content-Type‘: ‘application/x-www-form-urlencoded‘ ???????????}, ???????????//get ???????????params: { ???????????????name: ‘itcast‘, ???????????????sex: ‘男‘ ???????????}, ???????????//post ???????????// data: ‘age=10‘ ???????????data: { // post 传参 ???????????????age: 10 ???????????} ???????}).success(function (info) { ???????????console.log(info); ???????}); ???}]);</script></body></html>
get方式
<!DOCTYPE html><html lang="en" ng-app="App"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body><ul ng-controller="DemoController"></ul><script src="../libs/angular.min.js"></script><script> ???var App = angular.module(‘App‘, []); ???App.controller(‘DemoController‘, [‘$scope‘, ‘$http‘, function ($scope, $http) { ???????$http({ ???????????url: ‘02.php‘, ???????????method: ‘get‘, ???????????params: { ???????????????name: ‘wqx‘ ???????????} ???????}).success(function (info) { ???????????console.log(info); ???????}); ???}]);</script></body></html>
post
<!DOCTYPE html><html lang="en" ng-app="App"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body><ul ng-controller="DemoController"></ul><script src="../libs/angular.min.js"></script><script> ???var App = angular.module(‘App‘, []); ???App.controller(‘DemoController‘, [‘$scope‘, ‘$http‘, function ($scope, $http) { ???????$http({ ???????????url: ‘03.php‘, ???????????method: ‘post‘, ???????????headers: { ???????????????‘Content-Type‘: ‘application/x-www-form-urlencoded‘ ???????????}, ???????????data: ‘age=19‘ ???????}).success(function (info) { ???????????console.log(info); ???????}); ???}]);</script></body></html>
Angular——$http
原文地址:https://www.cnblogs.com/wuqiuxue/p/8423318.html