donglang1976 2016-04-04 11:39
浏览 51
已采纳

too long

I am sending data from javascript to my php server. But I can't access all my variables sent. There are some nested arrays and JSON strings and I just can't figure out how to access them.

Here my code:

sender.js

$scope.report = {
    'title': '',
    'desc': '',
    'address': {
        'text': '',
        'lat': '',
        'lng': ''
    },
    'tags': ['none chosen']
};



function postToServer () {
var data = {
    'do': 'addNewReportToDatabase',
    'data': {
        'usr': userId,
        'report': JSON.stringify($scope.report)
    }
};
$http({
    url: $rootScope.server_url,
    method: "POST",
    data: data,
    headers: {'Content-Type': 'application/json'}
}).then(function successCallback(response) {
    console.log(response);
}, function errorCallback(response) {
    alert(response);
});
}

server.php

$postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
    $data = json_decode(json_encode($request->data), True);
    if (isset($request->do)) {
        switch ($request->do) {
            case 'addNewReportToDatabase':
                $reportStr = $data['report'];
                $reportJSON = json_decode($reportStr);
                echo $reportJSON['title'];
                break;
        }
    } 

I can't access any variables of my report-variable.

I CAN say echo json_encode($reportJSON); and if I log it in my JS the response I get is an Object with all my variables as it's supposed to be!

The stringified version looks then like this: {"title":"title","desc":"describtion","address":{"text":"address","lat":"","lng":""},"tags":["Unfall","Terrorismus","Regional"]}

If I user var_dump($reportJSON); I get the following output:

"object(stdClass)#3 (4) { ["title"]=> string(5) "title" ["desc"]=> string(11) "describtion" ["address"]=> object(stdClass)#4 (3) { ["text"]=> string(7) "address" ["lat"]=> string(0) "" ["lng"]=> string(0) "" } ["tags"]=> array(3) { [0]=> string(6) "Unfall" [1]=> string(11) "Terrorismus" [2]=> string(8) "Regional" } } "

So why can't I access the variables with my php??

  • 写回答

2条回答 默认 最新

  • drmq16019 2016-04-04 11:48
    关注

    You are accessing report as an Associative array instead of an object.

    Your echo $reportJSON['title'] should be insetead:

    echo $reportJSON->title;

    since in your var_dump, $reportJSON is of type: object(stdClass)#3....

    Personally I like to work with JSON data as objects, kind of makes the code easier to read and avoids Undefined indexes notices on some cases.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?