php - 使用 PHP 和 AJAX 将数据写入文件不起作用

标签 php jquery ajax

我尝试使用 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/

相关文章:

php - mock php测试中的碳对象

php - 回显更新值而不是旧值

jQuery 表单验证正则表达式,以符号计数开头

javascript - 输入类型=文件未使用 Jquery 验证插件传递到 php 页面

javascript - Jquery 菜单 ul 切换

php - 使用 PHP 在电子邮件中发送长链接

php - 如何使用 PHP 从 MySQL 中提取信息?

jquery - 纯 CSS 图像平移

javascript - 使用 Javascript 和 RGBA 更改背景颜色渐变

php - jQueryUI 自动完成功能不起作用