Answers:
HTTP GET请求不能包含要发布到服务器的数据。但是,您可以将查询字符串添加到请求中。
angular.http为此提供了一个选项params
。
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
请参阅:http : //docs.angularjs.org/api/ng.$http#get和https://docs.angularjs.org/api/ng/service/$http#usage(显示params
参数)
$http.get(url.details_path, {params: {user_id: user.id}})
。
您可以将参数直接传递给$http.get()
以下项目
$http.get(user.details_path, {
params: { user_id: user.id }
});
从AngularJS v1.4.8开始,您可以使用
get(url, config)
以下方法:
var data = {
user_id:user.id
};
var config = {
params: data,
headers : {'Accept' : 'application/json'}
};
$http.get(user.details_path, config).then(function(response) {
// process response here..
}, function(response) {
});
对于那些对在GET请求中发送参数和标头感兴趣的人的解决方案
$http.get('https://www.your-website.com/api/users.json', {
params: {page: 1, limit: 100, sort: 'name', direction: 'desc'},
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
完整的服务示例如下所示
var mainApp = angular.module("mainApp", []);
mainApp.service('UserService', function($http, $q){
this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {
var dfrd = $q.defer();
$http.get('https://www.your-website.com/api/users.json',
{
params:{page: page, limit: limit, sort: sort, direction: direction},
headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
if ( response.data.success == true ) {
} else {
}
}, function(x) {
dfrd.reject(true);
});
return dfrd.promise;
}
});
您甚至可以简单地将参数添加到url的末尾:
$http.get('path/to/script.php?param=hello').success(function(data) {
alert(data);
});
与script.php配对:
<? var_dump($_GET); ?>
导致以下JavaScript警报:
array(1) {
["param"]=>
string(4) "hello"
}
这是一个在ASP.NET MVC中使用angular.js使用参数的HTTP GET请求的完整示例:
控制器:
public class AngularController : Controller
{
public JsonResult GetFullName(string name, string surname)
{
System.Diagnostics.Debugger.Break();
return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
}
}
视图:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.GetFullName = function (employee) {
//The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue
$http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
success(function (data, status, headers, config) {
alert('Your full name is - ' + data.fullName);
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="text" ng-model="name" />
<input type="text" ng-model="surname" />
<input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>
params
比“手动”的URL的concat容易发生误差小