我只想在服务器上的文件中保存一些JSON(使用Javascript生成).但我甚至不能使用简单的字符串:
HTML文件:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<style>
#test{
padding:20px 50px;
background:#ccc;
color:#000;
}
</style>
<script>
$(function(){
$('#test').click(function(){
$.ajax({
url: "page.php",
data: {"foo": "bar"},
processData: false,
contentType: 'application/json'
});
});
});
</script>
</head>
<body>
<div id="test">
KLICK
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
而php文件是这样的:
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fwrite($fh,$_POST['data']);
fwrite($fh,$_POST['foo']);
fwrite($fh,$_POST["foo"]);
fwrite($fh,$_POST[foo]);
fclose($fh);
Run Code Online (Sandbox Code Playgroud)
没有任何效果.我也试过了
$.ajax({
var datatosend="foo bar";
url: "page.php",
data: datatosend,
processData: false
});
Run Code Online (Sandbox Code Playgroud)
我不知道会出现什么问题.单击html文件中的div后,txt文件就在那里.但文件中没有内容.如果我只是将$ _POST写入文本文件,该文件包含Text"Array",这意味着$ _POST有一些内容.
这里很少有事情可能出问题。检查您尝试写入的目录的权限。还要确保您的 ajax 调用使用 POST 方法。
\n\n$.ajax({\n url: "page.php",\n type : \'POST\',\n ...\n}); \nRun Code Online (Sandbox Code Playgroud)\n\n正如jQuery 文档中所述,type 参数设置请求类型,POST 或 GET。
\n\n\n\n\n发出请求的类型(“POST”或“GET”),默认为“GET”。
\n
另一件需要考虑的事情是您实际上并没有编写 JSON 数据。数据以该格式发送,但当它到达$_POST变量时,它已被转换为数组。你应该尝试做的是将 PHP 数组写入文件 -
$fh = fopen($myFile, \'w\');\nfwrite($fh,\'<?php $arr=\'.var_export($_POST[\'data\'],true).\' ?>\');\nfclose($fh);\nRun Code Online (Sandbox Code Playgroud)\n\n这应该会给出一个与此类似的文件 -
\n\n<?php\n $arr = array(\n \'foo\'=>\'bar\'\n )\n?>\nRun Code Online (Sandbox Code Playgroud)\n\n正如您所看到的,该var_export()函数返回变量的可解析版本。
var_export()\n\nvar_export \xe2\x80\x94 输出或返回变量的可解析字符串表示形式
\n
| 归档时间: |
|
| 查看次数: |
16197 次 |
| 最近记录: |