我尝试使用 AJAX 和 PHP 将 json 数据保存到文件中,但生成的文件为空。为什么不起作用?
这是 HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
var dataset = {"value1": 2, "value2": 1000};
$.ajax({
url: 'save.php',
type: 'POST',
data: dataset,
success: function() {
alert('Success');
}
});
</script>
</body>
</html>
保存.php:
<?php
$map=json_decode($_POST['json_string']);
$file = "test.json";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $map);
fclose($fh);
?>
最佳答案
您使用了错误的 POST 变量名称。首先,发送您的 AJAX 请求:
data: {
json: dataset
},
然后使用:
$map = $_POST['json'];
不要解码它,因为您想保存 JSON 字符串,而不是数组。如果您想要 PHP 表示,最好使用 var_export()
:
$map = var_export(json_decode($_POST['json'], true), true);
关于php - 使用 PHP 和 AJAX 将数据写入文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12539509/