发布于2024-10-31 09:33 阅读(1009) 评论(0) 点赞(28) 收藏(4)
我对 PHP 不太熟悉,但我正在尝试将内容写入文件。由于某种原因,内容已写入文件,但仍返回“无法写入文件!”和 400 状态代码。但内容已成功写入文件。如何做到?
php代码(update.php):
<?php
//get root and page of request
$content_root = $_SERVER['DOCUMENT_ROOT'] . '/Animagie/content';
$page = $_POST['page'];
//open the correct contentfile
$content_file = fopen($content_root . '/' . $page, 'w');
if (isset($_POST[$page . '-content'])) {
if (fwrite($content_file, $_POST[$page . '-content']) === FALSE ) {
echo 'failed to write to file!';
fclose($content_file);
http_response_code(400);
} else {
fclose($content_file);
http_response_code(200);
}
} else {
echo 'something went wrong!';
fclose($content_file);
http_response_code(400);
}
?>
我使用以下代码调用 update.php:
editor.addEventListener('saved', function(e) {
var name, payload, regions, xhr;
//check if something changed
regions = e.detail().regions;
if (Object.keys(regions).length === 0) {
return;
}
//set editor busy while saving
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
payload.append('page', getCurrentPage());
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the updated content to the server to be saved
function onStateChange(e) {
//check if request is finished
if (e.target.readyState === 4) {
editor.busy(false);
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
}
}
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '../api/update.php');
xhr.send(payload);
});
您可能已经注意到,获取正确的状态代码非常重要,因为我会检查它并向用户返回是否成功。有人能帮助我吗?
提前致谢!
显然问题出在 javascript 检查上:
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
应该是
if (e.target.status == 200) {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
此外,在我切换 if 语句之后(如 @Jon Stirling 所述),postman 尚未刷新。因此,部分原因是服务器端的 if 语句错误,而客户端的 if 语句错误。
作者:黑洞官方问答小能手
链接:http://www.phpheidong.com/blog/article/551310/ddc33083db93d877bc84/
来源:php黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 php黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-4
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!