So i try to post a new node to a json file.
Here is my 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");
}
});
And here is the php file
$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";
The problem is the JSON file displays this:
{"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]"]}
Seems like your $markerData
has additional nested objects that need to be read explicitly and added to the json explicitly. You need to target those objects' properties and add them one by one.
If you were to echo $_POST['marker']
you would get [object Object]
but if you print it like this:
echo "<pre>";
print_r($_POST['marker']);
echo "</pre>";
Then you will see all of markers objects and properties and you can add them individually to your json or at least reference them in a for loop.
精彩评论