AngularJS中的$http服务用于向远程服务器发送HTTP请求并获取响应。语法如下:
$http({ method : 'HTTP方法', url : 'URL', params : '可选参数', data : '请求数据', headers : '请求头', responseType : '响应类型' }).then(function success(response) { // 处理成功响应 }, function error(response) { // 处理错误响应 });
参数说明:
示例:
// 发送一个GET请求,并处理响应 $http({ method : 'GET', url : 'https://jsonplaceholder.typicode.com/posts/1' }).then(function success(response) { console.log(response.data); }, function error(response) { console.log(response.statusText); });
// 发送一个POST请求,并处理响应 $http({ method : 'POST', url : 'https://jsonplaceholder.typicode.com/posts', data : { title: 'foo', body: 'bar', userId: 1 } }).then(function success(response) { console.log(response.data); }, function error(response) { console.log(response.statusText); });