2

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>

save.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);
?>
4

2 に答える 2

2

間違ったPOST変数名を使用しています。まず、AJAXリクエストを次のコマンドで送信します。

data: { 
    json: dataset
    },

そして、以下を使用します。

$map = $_POST['json'];

配列ではなくJSON文字列を保存するため、デコードしないでください。PHP表現が必要な場合は、次を使用することをお勧めしますvar_export()

$map = var_export(json_decode($_POST['json'], true), true);
于 2012-09-21T23:54:17.947 に答える
0

この行$map=json_decode($_POST['json_string']);$map=json_decode($_POST['dataset']);

于 2012-09-21T23:59:20.583 に答える