[英]Saving JSON with PHP script leaves file blank
我使用以下PHP脚本将一些JSON数据保存到JSON文件中:
<?php
$myFile = "json/countries.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_POST["data"];
fwrite($fh, $stringData);
fclose($fh)
?>
并使用此JS函数将数据发送到PHP脚本:
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!");}
});
}
但是唯一发生的是我尝试将数据保存到的JSON文件已清空。
如果我改变
data: { data:object },
至
data: { data:jQuery.parseJSON(object) },
我懂了
未捕获的SyntaxError:意外的令牌A
“ A”代表什么?
如果有人知道出了什么问题,请分享您的智慧:)
谢谢!
在您的php文件中尝试一下
<?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)
?>
将此添加到您的js文件中
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!");}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.