【问题标题】:Angularjs retrieving data issue while sending data by postAngularjs通过邮寄发送数据时检索数据问题
【发布时间】:2015-10-31 09:45:42
【问题描述】:

我将从 url 获得的 id 发送到服务器(php 页面)。

我从 url 获取并通过 angularjs 中的post 方法发送的方式:

注意: 我检索数据并在 console.log() 中打印正常,问题是我想将它们放入 $scope 的位置)

.controller('PlaylistCtrl', function($scope, $stateParams, $http) {
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    $http({
        method: 'POST',
        url: 'http://cms.focusweb.ir/Json/get_article',
        data: { id: $stateParams.playlistId },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    .success(function(response) {
        // This works right
        console.log(response);
        // PROBLEM IS HERE
        angular.forEach(response, function(response){
            $scope.articles_content.push(response);
        });

    })
    .error(function(data, status, headers, config) {
        // handle error things
    });
});

我的 PHP 代码是:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$article_ID = $request->id;

我得到的错误是:

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-service angularjs-http


    【解决方案1】:

    错误基本上是说articles_content 不存在(undefined)。因此'push' of undefined

    您需要在尝试使用之前定义您的数组。

    $scope.articles_content = []

    应该是这样的:

     .controller('PlaylistCtrl', function($scope, $stateParams, $http) {
    
        $scope.articles_content = []; // Add this in here
    
    
        $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
            $http({
                method: 'POST',
                url: 'http://cms.focusweb.ir/Json/get_article',
                data: { id: $stateParams.playlistId },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            })
            .success(function(response) {
                // This works right
                console.log(response);
    
                angular.forEach(response, function(response){
                  // because you now defined articles_content 
                  // as an array, the push() will now work :)
                  $scope.articles_content.push(response);
                });
    
            })
            .error(function(data, status, headers, config) {
                // handle error things
            });
        });
    

    $scope 已经定义好了,这就是为什么您可以动态地向其中添加任何内容的原因。比这更深层次的,你需要先定义你的结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      相关资源
      最近更新 更多