簡體   English   中英

javascript 在 then 塊中提交表單並使用 swal 從非異步 function 返回 false

[英]javascript submit form in then block and return false from a non-async function using swal

我正在嘗試使用onsubmit return myFunc()提交表單,但我也想在 function 中使用 swall。 這是我的代碼的樣子。 <form action="./script.php" onsubmit"return myFunc()"> </form>

let userName = $("#userName")
// use some validation here and finally

swal({
     title: "Are you sure",
     text: "Some Text"
     buttons: ['No', 'Yes']
     }).then((result) { 
         if(result) {
              console.log("Here we are!! ")
              return true
             // This is when I want the form to be submitted other wise return false
         } else {return false}        
    })
return false;
}    

發生的情況是 function 返回 false 並且從不執行 .then 塊中的代碼。

代碼中有一些語法錯誤。 then參數中缺少function關鍵字或=> ,並且swal()的參數列表中缺少逗號。 除此之外,在混合同步和異步任務時邏輯不起作用。

實際的事件監聽器是onsubmit屬性的內容,它調用myFunc並將 function 返回的值返回給內部事件處理程序。 swal()調用返回一個 promise,然后在傳遞給then的回調 function 中對其進行處理。 swal調用因此是異步的,並且在用戶真正單擊警報框中的按鈕后執行回調 function。 那時, myFunc已經完成並返回false

要解決此問題,您必須在所有情況下阻止表單提交的默認操作,如果swal結果為“是”,則在傳遞給then的回調 function 中提交表單。 像這樣的東西:

 const form = document.querySelector('#form'); function myFunc(e) { e.preventDefault(); // Prevent the form submission in any case swal({ title: "Are you sure", text: "Some Text", buttons: ['No', 'Yes'] }).then((result) => { if (result) { console.log('Submit the form.') // form.submit(); // Uncomment this line to submit the form } else { console.log('No submission.') } }); } form.addEventListener('submit', myFunc);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script> <form id="form"> <input type="submit" value="Submit"> </form>

暫無
暫無

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

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