AngularJS $ http调用不输出数组

时间:2013-07-17 21:57:04

标签: angularjs

尝试通过AngularJS $ http调用获取关联数组,但是我没有获取实际数组,而是获取字符串“Array”。

这是我的$ http电话:

$http({
            method : 'POST', 
            url : '[myPHPfile].php', 
            data : 'data=' + $scope.placementID,
            headers : { 'Content-Type' : 'application/x-www-form-urlencoded' }
        }).success(function(data) {
            alert(data);
        });

这是[myPHPfile] .php(省略其他行):

echo someFunctionInAnotherFile($_POST['data']);

我知道我抓住了数组,因为在[myPHPfile] .php中调用echo var_dump(theArray)并在$ http调用的成功部分中调用alert(data),我得到:

array(8) { 
   ["id"]=> string(1) "2" 
   ["id_key"]=>
   string(1) "2"
   ...
}

但是没有var_dump,我在成功时做了一个警报(data [“id”]),没有任何反应。并且发出警报(data [1])我得到“r”,所以不确定为什么返回的数据变成一个名为“Array”的字符串。

我已经在[myPHPfile] .php和alert(JSON.parse(data))中尝试了echo json_encode(...)成功,但是这也没有用。

只是尝试访问一个简单的数组,但需要帮助。 :(

1 个答案:

答案 0 :(得分:-1)

这里有一些问题。

来自PHP的json_encode()应该可以工作,但要确保标头设置正确。

<?php 
   header('Content-type: application/json'); 
   echo json_encode(someFunctionInAnotherFile($_POST['data']));
?>

第二个问题是,如果数组是“关联”数组,则json_encode会将PHP“数组”转换为对象,否则为常规数组。

最后,显示原始帖子数据非常危险,你不应该这样做。