我想使用html GET请求在json文件中加载数据:
NutrixFactory.getNutrients(foodId).then(function(nutrients){
console.log('nutrients returned', nutrients);
// $scope.nutrients = $scope.nutrients || [];
$scope.nutrients.push(nutrients);
console.log('nutrients array', $scope.nutrients);
});
在服务器端,这是我的index.html文件:
http://www.example.com/xxx/?id={device}&time={time}&snr={snr}&station={station}&lat={lat}&lng={lng}&rssi={rssi}&data={data}&avgSnr={avgSnr}
data.json文件保持为空,有人可以解释一下为什么吗?
非常感谢!
答案 0 :(得分:1)
您正在手动编译JSON,这只是在寻找麻烦。使用json_encode
,它会为你做很多事情:
<?php
$data = [
'data' => [
'id' => $_GET['id'],
'data' => $_GET['data'],
'from' => $_GET['station'],
'lat' => $_GET['lat'],
'lng' => $_GET['lng']
]
];
if ( $fl = fopen('data.json','a')) {
fwrite($fl, json_encode($data));
fclose($fl);
} else {
echo 'Cannot open file';
}
?>
答案 1 :(得分:1)
来自@Farkie的初始代码。您可能还想要清理并验证是否已设置所有_GET索引,如果没有为它们抛出默认值。
<?php
$data = array(
'id' => $_GET['id'],
'time' => $_GET['time'],
'snr' => $_GET['snr'],
'from' => $_GET['station'],
'lat' => $_GET['lat'],
'lng' => $_GET['lng'],
'rssi' => $_GET['rssi'],
'data' => $_GET['data'],
'avgSnr' => $_GET['avgSnr'],
);
if( $fl = fopen( 'data.json', 'a+' ) ){
$stats = fstat( $fl );
if( $stats['size'] ){
$contents = fread( $fl, $stats['size'] );
$collection = @json_decode( $contents, true );
$collection = isset( $collection['data'] ) && is_array( $collection['data'] )
? $collection
: array( 'data' => array() );
} else {
$collection = array( 'data' => array() );
}
$collection['data'][] = $data;
ftruncate( $fl, 0 );
fwrite( $fl, json_encode( $collection ) );
fclose( $fl );
} else {
echo 'Cannot open file';
}