I'm saving some JSON data to a JSON file using this PHP script:
<?php
$myFile = "json/countries.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_POST["data"];
fwrite($fh, $stringData);
fclose($fh)
?>
And sending the data to the PHP script with this JS function:
saveJson(countries, '/save_countries_to_json.php');
function saveJson(object, file) {
$.ajax
({
type: "POST",
dataType : 'json',
async: false,
url: file,
data: { data:object },
success: function () {alert("Thanks!"); },
failure: function() {alert("Error!");}
});
}
But the only thing that happens is that the JSON file I'm trying to save the data to is emptied.
If I change
data: { data:object },
to
data: { data:jQuery.parseJSON(object) },
I get
Uncaught SyntaxError: Unexpected token A
What does the 'A' stand for?
If anyone knows what's wrong, please share your wisdom :)
Thanks!
Try this in your php file
<?php
$myFile = "json/countries.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = urldecode($_POST["data"]);
$stringData1 = json_encode(json_decode($stringData));
fwrite($fh, $stringData1);
fclose($fh)
?>
Add this in your js file
saveJson(countries, '/save_countries_to_json.php');
function saveJson(object, file) {
$.ajax
({
type: "POST",
dataType : 'json',
async: false,
url: file,
data: { data:object },
success: function () {alert("Thanks!"); },
failure: function() {alert("Error!");}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.