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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13760070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:50:24  来源:igfitidea点击:

AngularJS passing data to $http.get request

javascriptangularjsjavascript-framework

提问by Chubby Boy

I have a function which does a http POST request. The code is specified below. This works fine.

我有一个执行 http POST 请求的函数。代码在下面指定。这工作正常。

 $http({
   url: user.update_path, 
   method: "POST",
   data: {user_id: user.id, draft: true}
 });

I have another function for http GET and I want to send data to that request. But I don't have that option in get.

我有另一个用于 http GET 的函数,我想将数据发送到该请求。但是我在 get 中没有那个选项。

 $http({
   url: user.details_path, 
   method: "GET",
   data: {user_id: user.id}
 });

The syntax for http.getis

的语法http.get

get(url, config)

获取(网址,配置)

回答by fredrik

An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.

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

angular.http provides an option for it called params.

angular.http 为其提供了一个名为params.

$http({
    url: user.details_path, 
    method: "GET",
    params: {user_id: user.id}
 });

See: http://docs.angularjs.org/api/ng.$http#getand https://docs.angularjs.org/api/ng/service/$http#usage(shows the paramsparam)

请参阅:http: //docs.angularjs.org/api/ng.$http#gethttps://docs.angularjs.org/api/ng/service/$http#usage(显示params参数)

回答by Rob

You canpass params directly to $http.get()The following works fine

可以将参数直接传递给$http.get()以下工作正常

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

回答by Arpit Aggarwal

Starting from AngularJS v1.4.8, you can use get(url, config)as follows:

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) {
});

回答by Subodh Ghulaxe

Solution for those who are interested in sending params and headers in GET request

对在 GET 请求中发送 params 和 headers 感兴趣的人的解决方案

$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
});

Complete service example will look like this

完整的服务示例将如下所示

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;
   }

});

回答by Jeffrey Roosendaal

You can even simply add the parameters to the end of the url:

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

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

Paired with script.php:

与 script.php 配对:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

导致以下 javascript 警报:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}

回答by Denys Wessels

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

这是在 ASP.NET MVC 中使用 angular.js 的带有参数的 HTTP GET 请求的完整示例:

CONTROLLER:

控制器:

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);
    }
}

VIEW:

看法:

<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>

回答by moin khan

For sending get request with parameter i use

用于发送带有参数的获取请求,我使用

  $http.get('urlPartOne\'+parameter+'\urlPartTwo')

By this you can use your own url string

通过这个你可以使用你自己的 url 字符串