所以我尝试将新节点发布到json文件。
这是我的js:
var newDate = new Date;
var markerId = newDate.getTime();
var markerData = { 'id': markerId, 'lat':markerId, 'long':markerId };
$.ajax({
type: 'POST',
url: "dataPath.php",
data: {
marker: markerData
},
dataType: 'json',
async: false,
success: function(result)
{
alert("Added OK");
}
});
这是php文件
$dataPath = 'file_path';
$markerDataFile = 'adauga.json';
$markerText = file_get_contents($markerDataFile);
$markerList = json_decode($markerText,true);
if( !empty($_POST['marker']) ){
$markerData = $_POST['marker'];
$markerData['ip'] = $_SERVER['REMOTE_ADDR'];
$markerData['created'] = time();
$markerList['markers'][] = $markerData;
$markerText = json_encode($markerList);
file_put_contents($markerDataFile, $markerText);
echo json_encode($markerData);
}else{
echo "Invalid request";
问题是JSON文件显示:
{"markers":[{"id":"1310499027672","lat":"47.1405","long":"7.243839999999977","ip":"127.0.0.1","created":1310499032},"1object Object]","1object Object]","1object Object]","1object Object]","1object Object]","1object Object]","1object Object]","1object Object]"]}
答案 0 :(得分:0)
好像你的$markerData
有其他嵌套对象需要显式读取并显式添加到json中。您需要定位这些对象的属性并逐个添加它们。
如果你要回复$_POST['marker']
,你会得到[object Object]
,但是如果你这样打印出来的话:
echo "<pre>";
print_r($_POST['marker']);
echo "</pre>";
然后您将看到所有标记对象和属性,您可以将它们单独添加到您的json中,或者至少在for循环中引用它们。