Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS向$http.get请求传递数据_Javascript_Angularjs_Javascript Framework - Fatal编程技术网

Javascript AngularJS向$http.get请求传递数据

Javascript AngularJS向$http.get请求传递数据,javascript,angularjs,javascript-framework,Javascript,Angularjs,Javascript Framework,我有一个函数可以执行http POST请求。下面指定了代码。这个很好用 $http({ url: user.update_path, method: "POST", data: {user_id: user.id, draft: true} }); 我还有一个http GET函数,我想向该请求发送数据。但我在get中没有这个选项 $http({ url: user.details_path, method: "GET", data: {user_i

我有一个函数可以执行http POST请求。下面指定了代码。这个很好用

 $http({
   url: user.update_path, 
   method: "POST",
   data: {user_id: user.id, draft: true}
 });
我还有一个http GET函数,我想向该请求发送数据。但我在get中没有这个选项

 $http({
   url: user.details_path, 
   method: "GET",
   data: {user_id: user.id}
 });
http.get
的语法是


get(url,config)

HTTP get请求不能包含要发布到服务器的数据。但是,您可以向请求中添加查询字符串

angular.http为它提供了一个名为
params
的选项

$http({
    url: user.details_path, 
    method: "GET",
    params: {user_id: user.id}
 });
请参阅:和(显示
参数)

您可以将参数直接传递到
$http.get()
以下操作正常

$http.get(user.details_path, {
    params: { user_id: user.id }
});

您甚至可以简单地将参数添加到url的末尾:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});
与script.php配对:

<? var_dump($_GET); ?>

对于那些对在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;
   }

});

从AngularJS v1.4.8开始,您可以使用 详情如下:

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('urlPartOne\\'+parameter+'\\urlPartTwo')

这样,您就可以使用自己的url字符串了。下面是一个完整的HTTP GET请求示例,其中包含ASP.NET MVC中使用angular.js的参数:

控制器:

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>
查看:

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>

var myApp=angular.module(“app”,[]);
myApp.controller('controller',函数($scope,$http){
$scope.GetFullName=函数(员工){
//url如下所示-ControllerName/ActionName?name=nameValue&name=nameValue
$http.get(“/Angular/GetFullName?name=“+$scope.name+”&姓氏=“+$scope.姓氏”)。
成功(函数(数据、状态、标题、配置){
警报(“您的全名为-”+data.fullName);
}).
错误(函数(数据、状态、标题、配置){
警报(“AJAX请求期间发生错误”);
});
}
});


这将返回一个promise,该代码带有承诺:$http({method'GET',url:'/someUrl'})。成功(函数(数据、状态、头、配置){//响应可用时,将异步调用此回调})。错误(函数(数据、状态、标题、配置){//如果发生错误,异步调用//或者服务器返回带有错误状态的响应。});Angular还提供了
$http.get(url.details\u path,{params:{user\u id:user.id}}})
中的功能。在http谓词之间保持对象键一致会很好。。。将数据用于POST和参数用于GET是违反直觉的。@HubertPerron实际上这并不违反直觉,因为它们是不同的东西:数据可以表示对象/模型,甚至是嵌套的,并成为POST标题的一部分。。。参数表示可以添加到GET url的内容,其中每个属性表示url中查询字符串的一部分。它们有不同的命名是很好的,因为这会让你意识到你在做不同的事情。$http有转义吗?这也可以,但问题是,当你有多个参数时,将它们添加到url的末尾会很痛苦,而且如果你更改了一个变量名,你必须来更改它还有网址,我知道。这更像是一个演示,表明你甚至可以用常规的方式来做,我不一定推荐。(其中“regular way”表示您可能已经使用php多年了)这是可行的,但params对象正在转换为字符串。如何保留原始对象?@wdphd HTTP固有的特性是将其编码为查询string@Uli克勒:是的,错过了这个。我一直在考虑UI路由器,您可以在其中指定参数数据类型。通过在后端使用简单的parseInt修复了此问题。如果您想将GET参数添加到给定的URL,这是一个正确的解决方案,并且效果非常好。@Juan,但此数据仍然不在请求正文中。@naXa GET仅根据约定应为URL参数,因此许多框架不允许它强制实施最佳做法,即使从技术上讲,它也可以工作并且有意义。如果AngularJS文档能够提供这个简单的例子就好了@Arpit Aggarwal您能帮我看看golang web server和vue.js的类似问题吗?控制器中如何使用响应数据?Thank.IMHO带有
params
的语法比“手动”url concat更不容易出错