Ajax打开(post)不更新文件
Ajax open(post) does not update the file
我需要一个html页面,保存一些数据在服务器文件(upated_data.php)。我已经按照使用AJAX的说明进行了操作,但是服务器文件保持不变。你能帮我找到下面代码中的问题吗?
<!doctype html>
<html>
<head><title>test</title></head>
<body>
<script>
var data = '{"data": "..."}';
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = warn_saving;
xmlhttp.open("POST","updated_data.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
function warn_saving() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
alert(xmlhttp.responseText);
}
</script>
</body>
</html>
我在服务器端的文件是:
-rw-r--r-- 1 www-data www-data 493 jun 5 15:42 test.html
-rw-r--r-- 1 www-data www-data 1 jun 5 15:43 updated_data.php
您试图将数据放入文件中,这不是AJAX实际做的。
如果要将数据添加到文件中,则必须使用PHP,如
$handle = fopen( 'path/to/file.txt', 'w' );
fwrite( $handle, $data );
fclose( $handle );
参考:http://www.w3schools.com/php/func_filesystem_fopen.asp
您可能必须更改$data
变量以表示应该保存到文件中的方式。也许你还想改变第二个mode
参数,它描述了如何处理文件以及在哪里设置指针:
w Mode =只写,并将指针指向起始,不存在则创建文件,否则删除全部内容
您的数据:Hello World
THIS IS A TEXT
^
是
Hello World
^
a Mode = Write only,并设置指针指向文件的END。如果文件不存在,创建一个
您的数据:Hello World
THIS IS A TEXT
^
是
THIS IS A TEXTHello World
^
我希望你明白,我不能把事情的全部答案给你,但这应该极大地帮助你找到真正的方法去做,并学会理解它
感谢前面的建议,我相信我已经得到了正确的代码。现在test.html调用存储在updated_data.php中的PHP代码:
<!doctype html>
<html>
<head><title>test</title></head>
<body>
<script>
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","updated_data.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText);
}
var d = '{datos: cosa}';
xmlhttp.send('data='+d);
</script>
</body>
</html>
和updated_data.php保存updated_data.json
<?php
$v = $_POST['data'];
file_put_contents('updated_data.json', json_encode($v));
?>
相关文章:
- 通过CSV文件上载更新数据库表
- 如何检查Json文件更新,如果更新了,则用更新的数据刷新我的页面
- Glassfish没有更新JavaScript文件
- JavaScript 不会更新文件
- 如何更新文件中的 JSON 数据
- 从javascript运行php更新文件
- 通过 IFrame 更新文件时的错误处理
- 无法通过 nodejs 读取更新文件的属性
- 节点.js更新文件中的 JSON 数据
- 露天更新文件 - 错误开机自检
- 为对事件更新文件的相同调用刷新浏览器缓存
- 在javascript中部分更新文件上传页面
- 上传或更新文件匹配表中行的objectId
- Filereader API在第一次更改后没有更新文件
- 更新文件时不需要重启Node.js中的服务器
- 插入和更新文件在谷歌驱动器与javascript
- 驱动器API:更新文件时的DeadlineExceededException
- 更新文件时触发来自 gulpfile 的更新
- Ajax打开(post)不更新文件
- 如果修改了Nginx更新文件