如何在angularjs中使用参数进行ajax调用

How to make a ajax call in angularjs with paramaters

本文关键字:参数 ajax 调用 angularjs      更新时间:2023-09-26

我试图通过ajax调用在angularjs中获取用户位置,但我得到语法错误

app.controller('locationController', function($scope, $window) {
  $window.navigator.geolocation.getCurrentPosition(function(position) {
    console.log(position);
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    $scope.$apply(function() {
      $scope.lat = lat;
      $scope.long = long;
    });
  });
  var city = function() {
    http.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="
      lat ","
      long "&sensor=true").success(function(response) {
      console.log(response);
    });
  }
});

我得到的错误是标记的语法错误,删除这个标记

我看到了至少三个问题:

  1. 似乎你没有正确连接字符串在你的http.get呼叫。
  2. 据我所知,
  3. latlong不在city函数的范围内。你可能打算使用$scope.lat$scope.long ?
  4. http是一个服务,你没有注入它。

    app.controller('locationController', function($scope, $window, $http) {    
       $window.navigator.geolocation.getCurrentPosition(function(position) {
          console.log(position);
          var lat = position.coords.latitude;
          var long = position.coords.longitude;
          $scope.$apply(function() {
             $scope.lat = lat;
             $scope.long = long;
         });
      });
      var city = function() {
        $http.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="
           + $scope.lat + ","
           + $scope.long + "&sensor=true").success(function(response) {
              console.log(response);
        });
      }
    });
    

试试这个,$http需要添加…Angularjs支持2种ajax方法。一种是严格的函数调用(4种操作类型,get, post, update, delete)或添加一个配置对象,如$.ajax。

app.controller('locationController', function($scope, $window, $http) {  // updated
    var city = function() {
    $http.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="  // updated
      lat ","
      long "&sensor=true").success(function(response) {
      console.log(response);
    });
  }
}