How to pass parameters to $http in angularjs?

前端 未结 4 1478
囚心锁ツ
囚心锁ツ 2020-12-04 23:45

Assume that I have two input boxes with corresponding ng-model as fname and lname. If I call http request as :

$http({method:\'GET\', url:\'/search\', params         


        
相关标签:
4条回答
  • 2020-12-05 00:16

    We can use input data to pass it as a parameter in the HTML file w use ng-model to bind the value of input field.

    <input type="text" placeholder="Enter your Email" ng-model="email" required>
    
    <input type="text" placeholder="Enter your password " ng-model="password" required> 
    

    and in the js file w use $scope to access this data:

    $scope.email="";
    $scope.password="";
    

    Controller function will be something like that:

     var app = angular.module('myApp', []);
    
        app.controller('assignController', function($scope, $http) {
          $scope.email="";
          $scope.password="";
    
          $http({
            method: "POST",
            url: "http://localhost:3000/users/sign_in",
            params: {email: $scope.email, password: $scope.password}
    
          }).then(function mySuccess(response) {
              // a string, or an object, carrying the response from the server.
              $scope.myRes = response.data;
              $scope.statuscode = response.status;
    
            }, function myError(response) {
              $scope.myRes = response.statusText;
          });
        });
    
    0 讨论(0)
  • 2020-12-05 00:18

    Build URL '/search' as string. Like

    "/search?fname="+fname"+"&lname="+lname
    

    Actually I didn't use

     `$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}})` 
    

    but I'm sure "params" should be JSON.stringify like for POST

    var jsonData = JSON.stringify(
        {
            fname: fname,
            lname: lname 
        }
    );
    

    After:

    $http({
      method:'GET',
      url:'/search',
      params: jsonData
    });
    
    0 讨论(0)
  • 2020-12-05 00:20

    Here is a simple mathed to pass values from a route provider

    //Route Provider
    $routeProvider.when("/page/:val1/:val2/:val3",{controller:pageCTRL, templateUrl: 'pages.html'});
    
    
    //Controller
    $http.get( 'page.php?val1='+$routeParams.val1 +'&val2='+$routeParams.val2 +'&val3='+$routeParams.val3 , { cache: true})
            .then(function(res){
                //....
            })
    
    0 讨论(0)
  • 2020-12-05 00:40

    Here is how you do it:

    $http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
        .then(function (response) { /* */ })...
    

    Angular takes care of encoding the parameters.

    Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData} is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).

    0 讨论(0)
提交回复
热议问题