首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在没有硬页面刷新的情况下将fetch() POST请求提交到输出数据库数据后使用fetch() GET请求

在没有硬页面刷新的情况下将fetch() POST请求提交到输出数据库数据后使用fetch() GET请求
EN

Stack Overflow用户
提问于 2022-05-04 22:24:40
回答 4查看 1.9K关注 0票数 7

我有一个表单,它用javascript fetch() API向MySQL数据库提交数据。

在下面的代码中,当表单提交时,会在页面上输出一条成功消息,并通过fetch() API防止硬刷新。

板模块本身最初是通过单击事件显示在一个‘添加到董事会’元素。

因为主板列表是在while循环中输出到页面上的,所以我希望它能够在不刷新页面的情况下在循环中输出新的板名。我想我可以通过在一个单独的GET函数中添加一个简单的fetch()请求来做到这一点。但这不起作用(我也没有收到任何错误消息)。

当页面发生硬刷新时,添加到输出列表中并如预期的出现在页面上的新板,因此我知道PHP在后端运行正常。

** 编辑 **

我已经输入了我尝试过的原始代码,这与@willgardner的回答基本相同。

因为我对fetch()和AJAX一般还是比较陌生的--我是否打算(用JavaScript)在表单中构造一个新的按钮元素,以显示来自get请求的更新结果?我假设PHP循环会在发生get请求时将其输出到页面上?就像最初加载页面时一样吗?

我还忽略了HTML中的输入元素,该元素用于post数据库中的一个板名,然后该名称将与get请求一起取回。现在已经添加了这个元素,它是create-board-name输入元素。

JavaScript

代码语言: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都可以工作,因为当硬页面刷新发生时,页面返回正确的数据。

代码语言:javascript
复制
<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>
EN

回答 4

Stack Overflow用户

发布于 2022-05-07 08:10:02

这看起来像是你在JavaScript中的承诺的一个问题。我在下面添加了一些评论,以说明问题的所在。

本质上,GET获取请求是在POST提取请求完成之前运行的,因此GET fetch请求不会返回POSTed的新数据,因为它还不存在于数据库中。

代码语言:javascript
复制
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请求的链接承诺中来解决这个问题:

代码语言: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);

      /**
       * 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);
        });
    }
  });
}

如果您觉得这有点混乱,并且想要避免回调地狱,您可以切换到使用异步/等待语法而不是.then(),但这当然是完全可选的!

票数 2
EN

Stack Overflow用户

发布于 2022-05-11 08:58:13

要求

据我所知,你有,

  1. 列出数据库中的一些板的页面。
  2. POST请求向DB添加新数据。

你想要的是,

  1. 执行将数据添加到DB的post请求
  2. 完成后,执行GET请求以获取新标记
  3. (缺少此步骤)使用新获取的标记并用新标记替换页面内容。

简介

使用fetch向URL发出的请求将与该页面的内容一起解析。你如何处理这些内容取决于你自己。

在您的代码中,您没有使用它做任何事情。

想法

因此,在get请求之后,您需要获取数据并将其填充到文档中。

代码语言:javascript
复制
fetch( pagePath, {method: "get"} )
    .then( function ( response ) {
        return response.text();
    } )
    .then( htmlResponse => {
        // Use the data to populate into current document
        populateHTMLDataToPage( htmlResponse );
    } );

函数populateHTMLDataToPage

但是等等,我们没有任何populateHTMLDataToPage函数!

这个功能是解决问题的关键。函数应该解析新接收的数据并将其放入页面。

一个快速但肮脏的方法是用收到的新内容替换页面上的所有内容。这很简单,但很脏,因为它将删除之前添加的所有事件处理程序。

代码语言:javascript
复制
function populateHTMLDataToPage( htmlResponse ) {
    document.open();
    document.write( htmlResponse );
    document.close();
}

这意味着您需要将事件处理程序重新附加到页面上,因为所有元素都已更改。

您需要的是更好地实现populateHTMLDataToPage函数。理想情况下,您希望只针对具有更新内容的元素。在包含循环数据的列表/包装中使用类/ID。为了简单起见,让我们假设所有循环数据都在<div id='boards'></div>中,

  1. htmlResponse解析为html,相对容易使用jQuery。
  2. #boards中查找htmlResponse元素并获取其innerHTML。
  3. 在您的页面中找到#boards,并将其替换为新的innerHTML。

因此,您可以通过使用提供的populateHTMLDataToPage函数来测试解决方案的合理性。在替换所有内容后重新附加事件处理程序的路径上。或者开发更好的populateHTMLDataToPage,它只更新需要更新的部分。

票数 2
EN

Stack Overflow用户

发布于 2022-05-09 18:52:38

PHP代码只在最初加载页面时在服务器上运行。当您在客户端手动处理fetch GET请求时,JavaScript代码将完全不运行。因此,是的,您需要在JavaScript中手动构造DOM元素,用从服务器响应获得的信息填充它们,然后将它们插入DOM中。

如果不知道服务器响应和DOM的确切形状,很难提供确切的示例,但下面是如何从基于json的服务器响应中读取"name“属性,并将其插入到位于<ul id="myList">元素末尾的新<ul id="myList">中。

代码语言:javascript
复制
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);
 })
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72120078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档