用AngularJS发布不起作用

用AngularJS发布不起作用

我想向我的api发送一个post请求。它与jquery一起工作:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
  $.ajax({
  type: "POST",
  url: "api.php?option=inscription",
  data: {lol : "mess"}
});
</script>

但安格拉的情况并非如此:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">    </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>

如果有人能帮我。谢谢您!
更新:
谢谢你的回答,我想简化,但现在不清楚了。所以在你的帮助下,这是我的新代码,问题也是一样的。后端数据为空;
前端:
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">   </script>

<div ng-controller="MainCtrl"></div>
{{data}}

<script>
var app = angular.module('myApp', []);

app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {

    var back =  $http.post(dataUrl, dataTobePosted);

    back.success(function(data){
      console.log(data);
      return data;
    }).error(function(data, status, headers, config) {
      return status;
});
    }
});

app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
    var dataTobePosted = {"lol": "mess"};

    $scope.data = SomeService.readData(url, dataTobePosted);
}

$scope.readData('api.php?option=inscription');
});
</script>
</html>

最佳答案

为了清楚起见,我建议一个简单的实现。然而,可能需要进一步阅读,以便准确理解行为。

angular.module('myApp').service('SomeService', function($http) {
    this.readData = function(dataUrl, dataTobePosted) {
        // read data;
        return $http.post(dataUrl, dataTobePosted)
            .then(function(res) {
                return res.data;
            }, function(res) {
                return res;
            }
    }
    return this;
});

angular.module('myApp').controller('MyController', function($scope, SomeService) {
    $scope.readData = function(url) {
        var dataTobePosted = {"lol": "mess"};

        SomeService.readData(url, dataTobePosted)
        .then(function(res) {
            $scope.data = res;
        }, function(res) {
            // Display error
        }
    }

    $scope.readData('api.php?option=inscription');
}

在HTML页面中的使用
<div ng-controller="MyController">
    {{data}}
</div>

关于ajax - 用AngularJS发布不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30050900/

10-09 20:36