PHP的json响应在angular $http中是未定义的

PHP json response is undefined in angular $http

本文关键字:http 未定义 angular json 响应 PHP      更新时间:2023-09-26

我们还在学习angular js是如何工作的,我们没有什么问题,我们正在用angular

做一个http post请求。
var app = angular.module('app',['ngMessages']);
app.controller('AppCntrl', function($scope, PostingService) {
  $scope.submitData = function() {
    var data = {
      name: "abc",
      email: "email@example.com"
    };
    PostingService.postData(data);
  }
});
app.service('PostingService', ['$http',function($http) {
  this.postData = function(data) {
    $http.post(
      '/url/to/post/request',
      data
    )
      .then(function successCallback(response) {
      alert(response); // alerts undefined ***********************
    }, function errorCallback(response) {
      alert(response); // alerts undefined ***********************
    });
  }
}]);

/url/to/post/request的输出为header('Content-Type:application/json;');, json响应为{"status":true,"message":"this is message"},但警报显示未定义

我做了一些改变,但这应该无关紧要。这段代码似乎可以工作。>修改变量requestURI

var app = angular.module('app', [])
app.controller('AppCtrl', function($scope, PostingService) {
  $scope.submitData = function() {
    var data = {
      name: 'abc',
      email: 'email@example.com'
    }
    PostingService.postData(data)
  }
})
app.service('PostingService', ['$http', function($http) {
  var requestURI = ''
  this.postData = function(data) {
    $http.post(requestURI, data)
      .then(function(response) {
        alert(response)
      }, function(response) {
        alert(response)
      })
  }
}])
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>
  <body ng-app="app">
    <div ng-controller="AppCtrl">
      <button ng-click="submitData()">Make POST Request</button>
    </div>
  </body>
</html>