gpt4 book ai didi

javascript - PHP 写入文件可以工作,但显示错误

转载 作者:行者123 更新时间:2023-11-28 04:43:22 24 4
gpt4 key购买 nike

我对 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 语句。

关于javascript - PHP 写入文件可以工作,但显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43590709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com