我有一个使用 javascript fetch()
提交数据的表单使用 PHP 到 MySQL 数据库的 API。
在下面的代码中,当表单被提交时,页面上会输出一条成功消息,并且由于 fetch()
而阻止了硬刷新。 API。
板模块本身最初通过“添加到板”元素上的单击事件显示。
因为板列表输出到页面中的 while
循环,我想要它,所以新的板名也会在循环中输出,而无需刷新页面。我想我可以通过添加一个简单的 GET
来做到这一点在单独的 fetch()
中请求功能。但这不起作用(我也没有收到任何错误消息)。
当页面发生硬刷新时,新板将添加到输出列表中并按预期显示在页面上,所以我知道 PHP 在后端工作正常。
** 编辑 **
我已经输入了我尝试过的原始代码,这与@willgardner 的答案基本相同。
因为我对 fetch()
比较陌生和一般的 AJAX - 我是否打算(使用 JavaScript)构造一个新的按钮元素,该元素将显示来自 get
的更新结果要求?我假设 PHP 循环会在 get
时将其输出到页面上。请求发生?就像最初加载页面时一样?
我也错过了 HTML 中用于 post
的输入元素。数据库的板名,然后用 get
取回要求。现在已添加,是 create-board-name
输入元素。
JavaScript
// Use fetch() to prevent page doing hard refresh when a new board name is created
let boardModuleForm = document.querySelector('.board-module-form'),
// URL details
myURL = new URL(window.location.href),
pagePath = myURL.pathname
if (boardModuleForm) {
boardModuleForm.addEventListener('submit', function (e) {
if (e.submitter && e.submitter.classList.contains('js-fetch-button')) {
e.preventDefault();
const formData = new FormData(this);
formData.set(e.submitter.name, e.submitter.value);
fetch(pagePath, {
method: 'post',
body: formData
})
.then(function(response) {
if (response.status === 200) {
fetch(pagePath, {
method: 'get',
})
.then(function(response) {
return response.text();
}).catch(function(error) {
console.error(error);
})
}
return response.text();
})
.catch(function(error) {
console.error(error);
})
}
})
}
HTML 和一些 PHP 这一切正常,因为页面在发生硬页面刷新时返回正确的数据<form class="board-module-form" method="post">
<?php
if (isset($_SESSION['logged_in'])) {
$board_stmt = $connection->prepare("SELECT * FROM `boards` WHERE `user_id` = :id ORDER BY id DESC");
$board_stmt -> execute([
':id' => $db_id // variable created when user logs in
]);
while ($board_row = $board_stmt->fetch()) {
$db_board_id = htmlspecialchars($board_row['id']);
$db_board_name = htmlspecialchars($board_row['board_name']);
$db_board_user_id = htmlspecialchars($board_row['user_id']);
?>
<button class="board-list-item" name="board-name" type="submit">
<?php echo $db_board_name; ?>
</button>
<?php
}
}
?>
<div class="submit-wrapper">
<input id="board-name" name="create-board-name" type="text">
<button type="submit" name="submit-board-name" class="js-fetch-button">Submit Board</button>
</div>
</form>
最佳答案
这看起来像是您在 JavaScript 中的 promise 的问题。我在下面添加了一些评论以显示问题所在。
本质上,GET fetch 请求在 POST fetch 请求完成之前运行,因此 GET fetch 请求不会返回已发布的新数据,因为它尚不存在于数据库中。
if (boardModuleForm) {
boardModuleForm.addEventListener('submit', function (e) {
if (e.submitter && e.submitter.classList.contains('js-fetch-button')) {
e.preventDefault();
const formData = new FormData(this);
formData.set(e.submitter.name, e.submitter.value);
/**
* This is asynchronous. To ensure code is run after the (response) promise
* has resolved, it needs to be within the .then() chain.
*/
fetch(pagePath, {
method: 'post',
body: formData
})
.then(function (response) {
if (response.status === 200) {
// output success message
}
return response.text();
})
.catch(function(error) {
console.error(error);
})
// ----- GET REQUEST TO 'FETCH' NEW BOARD NAME FROM DATABASE
/**
* This will run immediately after the fetch method above begins.
* So it will run before the data you POST to the PHP is saved
* to the db, hence when you fetch it, it doesn't return
* the new data.
*/
fetch(pagePath, {
method: 'get',
})
.then(function (response) {
return response.text();
})
.catch(function(error) {
console.error(error);
})
}
})
}
您可以通过将 GET 获取请求移动到 POST 请求的链式 promise 中来解决此问题:// Use fetch() to prevent page doing hard refresh when a new board name is created
let boardModuleForm = document.querySelector(".board-module-form"),
// URL details
myURL = new URL(window.location.href),
pagePath = myURL.pathname;
if (boardModuleForm) {
boardModuleForm.addEventListener("submit", function (e) {
if (e.submitter && e.submitter.classList.contains("js-fetch-button")) {
e.preventDefault();
const formData = new FormData(this);
formData.set(e.submitter.name, e.submitter.value);
/**
* This is asynchronous. To ensure code is run after the (response) promise
* has resolved, it needs to be within the .then() chain.
*/
fetch(pagePath, {
method: "post",
body: formData
})
.then(function (response) {
if (response.status === 200) {
// ----- GET REQUEST TO 'FETCH' NEW BOARD NAME FROM DATABASE
/**
* This will now run after the POST request promise has resolved
* and new data successfully added to the db.
*/
fetch(pagePath, {
method: "get"
})
.then(function (response) {
return response.text();
})
.catch(function (error) {
console.error(error);
});
}
return response.text();
})
.catch(function (error) {
console.error(error);
});
}
});
}
如果你觉得这有点乱,你想避免callback hell您可以切换到使用 async/await syntax instead of .then()但这当然是完全可选的!
关于javascript - 在 fetch() POST 请求已提交后使用 fetch() GET 请求以输出数据库数据而无需硬页面刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72120078/