使用PHP脚本保存JSON将文件保留为空白 [英] Saving JSON with PHP script leaves file blank

查看:210
本文介绍了使用PHP脚本保存JSON将文件保留为空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下PHP脚本将一些JSON数据保存到JSON文件中:

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)
?>

并使用此JS函数将数据发送到PHP脚本:

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!");}
});
}

但是唯一发生的是我试图将数据保存到的JSON文件已清空.

But the only thing that happens is that the JSON file I'm trying to save the data to is emptied.

如果我更改

data: { data:object },

data: { data:jQuery.parseJSON(object) },

我知道

未捕获到的SyntaxError:意外的令牌A

Uncaught SyntaxError: Unexpected token A

"A"代表什么?

如果有人知道出了什么问题,请分享您的智慧:)

If anyone knows what's wrong, please share your wisdom :)

谢谢!

推荐答案

在您的php文件中尝试

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)
?>

将此添加到您的js文件中

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!");}
});
}

这篇关于使用PHP脚本保存JSON将文件保留为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆