簡體   English   中英

如何防止頁面在 JavaScript 獲取帖子請求后刷新?

[英]How to prevent page from refreshing after JavaScript fetch post request?

我正在從客戶端向 Flask API 發送一個文件。我嘗試執行 e.preventDefault()、e.stopPropagation(),並為表單上的“onsubmit”返回 false,但它仍然會刷新我需要的頁面web 保留 API 將發回的一些信息,但在頁面刷新后它會消失。 我試過使用本地存儲來存儲數據,但是當頁面刷新時它就消失了。 對不起,如果這是一個愚蠢的問題:祈禱:

Javascript

const form = document.querySelector("#upload-form");
const uploadBtn = document.querySelector("#upload-btn");
const uploadInp = document.querySelector("#upload-input");

const sendFile = async () => {
  let formData = new FormData();
  formData.append("file", uploadInp.files[0]);
  await fetch(apiPOST, {
    method: "POST",
    body: formData,
  })
    .then((res) => res.json())
    .then((json) => {
      console.log(json);
    })
    .catch((err) => console.log(err));
};

uploadBtn.addEventListener("click", (e) => {
  e.preventDefault();
  sendFile();
});

HTML

<form id="upload-form" enctype="multipart/form-data" method="post" onsubmit="return false">
     <label for="upload-input" class="btn">Upload File</label>
     <input type="file" id="upload-input" name="upload-input" accept=".pptx"/>
     <!-- <button id="upload-btn">Upload</button> -->
     <input type="submit" id="upload-btn" value="Upload" />
</form>

您應該從表單提交屬性調用 preventDefault 方法,而不是您的按鈕。

檢查此答案以獲取更多信息

有同樣的問題,我在其他問題中發布了答案。 看看它是否有用(這里)。 在我的情況下,問題是 db.json 中的更改觸發了實時服務器中的實時重新加載,通過分離客戶端和數據庫的文件夾來解決它。 更多細節在這里

我遇到了像 Ulises Rodriguez 一樣的問題,他度過了我的一天:D 在我的情況下,它確實導致 VSCode 中的 LiveServer 插件(它檢測到由 BE 生成的日志 json)。 當我關閉它時,preventDefault() function 開始工作,頁面在 POST 后停止重新加載。 這是代碼示例:

dbUploadForm.addEventListener('submit', async function(upload) {
upload.preventDefault();

    const postData = new FormData(this);
    const jsonData = JSON.stringify({
        sheet: sheet.value,
        headerRow: headerRow.value,
        dataStartRow: dataStartRow.value,
        databaseTable: selectdatabaseTable.getValue(),
        tableType: tableType.value,
        pageName: pageName.value
    });
    postData.append('jsonData', jsonData);
    postData.append('userFile', userFile.files[0]);

    const response = await fetch(API.admin.file.uploadExcelToDb, {
            method: 'POST',
            headers: {
                'credentials': 'same-origin',
                'X-Requested-With': 'XMLHttpRequest',
            },
            body: postData
        })
        .then((response) => response.json())
        .then((data) => {
            if (data) {
                buttonEnableHideSpinner(id("uploadButton"));
            }
            if (data['status'] === 200) {
                let validationAlert = new Alert({
                    message: data['message'],
                    displayInElement: id('alerts'),
                    result: 'success',
                    id: 'validationAlert'
                }).show()
            } else {
                let validationAlert = new Alert({
                    message: data['message'],
                    displayInElement: id('alerts'),
                    result: 'danger',
                    id: 'validationAlert'
                }).show()
            }
        });

}, 錯誤的);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM