我有一个表单,它用javascript fetch() API向MySQL数据库提交数据。
在下面的代码中,当表单提交时,会在页面上输出一条成功消息,并通过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>发布于 2022-05-09 18:52:38
PHP代码只在最初加载页面时在服务器上运行。当您在客户端手动处理fetch GET请求时,JavaScript代码将完全不运行。因此,是的,您需要在JavaScript中手动构造DOM元素,用从服务器响应获得的信息填充它们,然后将它们插入DOM中。
如果不知道服务器响应和DOM的确切形状,很难提供确切的示例,但下面是如何从基于json的服务器响应中读取"name“属性,并将其插入到位于<ul id="myList">元素末尾的新<ul id="myList">中。
fetch(pagePath, { method: "get" }).then(async function (response) {
const { name } = await response.json(); // This will only work if your server returns JSON in the body. If there's another shape to the data, you'll need to experiment/post additional details to your question.
const newListItem = document.createElement("li")
newListItem.innerText = name;
document.getElementById("myList").append(newListItem);
})https://stackoverflow.com/questions/72120078
复制相似问题