我正在将数据从javascript发送到我的php服务器。但是我无法访问所有发送的变量。有一些嵌套的数组和JSON字符串,我只是不知道如何访问它们。
这是我的代码:
$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);
});
}
$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;
}
}
我无法访问报告变量的任何变量。
我可以说echo json_encode($reportJSON);
,如果我将其记录在JS中,我得到的响应就是一个包含所有变量的对象!
字符串化的版本如下所示: {"title":"title","desc":"describtion","address":{"text":"address","lat":"","lng":""},"tags":["Unfall","Terrorismus","Regional"]}
如果我使用var_dump($reportJSON);
我,将得到以下输出:
"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" } } "
那为什么我不能用我的php访问变量呢?
您正在report
作为关联数组而不是对象进行访问。
您echo $reportJSON['title']
应该有勇气:
echo $reportJSON->title;
由于在您的中var_dump
,$reportJSON
类型为:object(stdClass)#3...
。
我个人喜欢将JSON数据作为对象使用,这种方式使代码更易于阅读,并且在某些情况下避免出现未定义索引的情况。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句