可以在Angular JS中的HTTP post请求中传递多个$ scope变量吗?

时间:2015-07-29 11:28:02

标签: javascript angularjs

  $scope.getQuery = function() {
    var response =  $http.post('/test/getQuery', $scope.query, $scope.algoName);
    response.success(function(data, status, headers, config) {
           console.log($scope.query);           
           console.log($scope.algoName);
        });
   }

我在这里传递$scope.query$scope.algoName。这在AngularJS中是否可行?

4 个答案:

答案 0 :(得分:4)

您可以data接受的$http.post()参数传递它们:

var data = {
    query: $scope.query,
    algoName: $scope.algoName
};

$scope.getQuery = function() {
    var response =  $http.post('/test/getQuery', data);
    response.success(function(data, status, headers, config) {
        console.log($scope.query);
        console.log($scope.algoName);
    });
};

然后将这些作为请求消息数据发送。

答案 1 :(得分:1)

$scope.getQuery = function() {    
    var data = {    
        query: $scope.query,   
        algoName: $scope.algoName   
    };

    var response =  $http.post('/test/getQuery', data);

    response.success(function(data, status, headers, config) {
        console.log($scope.query);
        console.log($scope.algoName);
    });
};

您的数据变量需要在您的函数中...可能是他直接调用函数....

答案 2 :(得分:0)

您需要此要求的原因是什么?通常需要在发送

之前构建数据响应对象
var data = {}
data.query = $scope.query;
data.algoName = $scope.algoName;

var response =  $http.post('/test/getQuery', data);

答案 3 :(得分:0)

Angular的$http最多可接受3个参数。

来自Angular docs

  

post(url,data,[config]);

data可能是您要传递给网址的任何内容,您基本上可以这样做:

$scope.getQuery = function() {
    // your endpoint
    var endpoint = '/test/getQuery';

    // data you want to sent the server
    var data = {
        query: $scope.query,
        algoName: $scope.algoName
    };

    // all your configs
    var config = {
        headers: {
            'Content-Type': 'application/json' // or whatever you need here
        }
    };

    // This makes the call, the .then deals with the promise
    // the first function is success and the second deals with fail
    $http.post(endpoint, data, config).then(function(response) {
        console.debug(response);
    }, function (error) {
        console.debug(error);
    });
};

另一种方法可以将其保存在变量中,然后解析它我更喜欢使用第一种方式,但是如果你想传递它是另一种方式。

var response = $http.post(endpoint, data, config);

response.then(function(response) {
    console.debug(response);
}, function (error) {
    console.debug(error);
});

请记住,$hhtp会返回一个承诺,而.then就是您解决它的方式,并提取延期信息。