【问题标题】:PHP json response is undefined in angular $httpPHP json响应在角度$ http中未定义
【发布时间】:2023-03-29 18:10:02
【问题描述】:

我们仍在学习 angular js 的工作原理,我们有一点问题,我们正在使用 angular 发出 http 发布请求

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"},但警报显示未定义

【问题讨论】:

    标签: javascript php angularjs json


    【解决方案1】:

    我做了一些更改,但没关系。这段代码似乎有效。 > 更改变量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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 2020-11-10
      相关资源
      最近更新 更多