簡體   English   中英

使用PHP腳本保存JSON將文件保留為空白

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM