簡體   English   中英

完成輸入后如何提交表格? (JavaScript異步)

[英]How to submit a form after you're done typing? (JavaScript async)

在用戶停止鍵入半秒鍾后,我需要提交一個表單提交。

您應該保持輸入的重點,並且如果再輸入幾個字符,它仍然可以繼續提交。

我更喜歡香草JS,jQuery也可以。

我嘗試使用onKeydown事件將超時設置為半秒,然后使用了preventDefault()form.submit()

 let searchText = document.getElementById('search_input'); searchText.onkeypress = function(e) { //alert("key down"); var event = e || window.event; var charCode = event.which || event.keycode; if (charCode == '13') { fnFillGrid(); return false; } } function fnFillGrid() { console.log('Lala'); } 
 <form action="#"> Search: <input id="search_input" type="search" name="q"> </form> 

我希望用戶能夠在輸入完畢后一秒鍾內輸入內容,以提交搜索。 焦點模糊應保留在輸入上,以便它們可以繼續鍵入/搜索。

這將觸發onkeyup ,我發現這是啟動自動搜索的最佳方法,如下所示:

 let searchText = document.getElementById('search_input'); searchText.addEventListener("keyup", search); let timeout = null; function search() { if (timeout) { window.clearTimeout(timeout); } timeout = setTimeout(function () { fnFillGrid(); }, 500); } function fnFillGrid() { console.log('Lala'); } 
 <form action="#"> Search: <input id="search_input" type="search" name="q"> </form> 

基本上,您需要捕獲最后鍵入的鍵與您的特定等待時間之間的時間。 在這種情況下,POST請求在無輸入1秒鍾后執行。 這將是一個真實的示例(發布到jsonplaceholder來模擬POST請求)。 您可以檢查網絡標簽(在開發工具中)以進行觀看。

還應該在這里指出不推薦使用KeyboardEvent.which (請參閱https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which

 const postMessage = async (message) => { const response = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ title: 'title', body: message, userId: 1 }), headers: { "Content-type": "application/json; charset=UTF-8" } }); return response.json(); } let time = null; const textBox = document.getElementById('myTextbox'); textBox.addEventListener('keyup', async (e) => { time = new Date().getTime(); setTimeout( async () => { const currentTime = new Date().getTime(); const timeDiff = currentTime - time; if (timeDiff >= 1000) { const response = await postMessage(textBox.value); console.log('response', response); } }, 1000); }); 
 <input type="text" id="myTextbox" /> 

該解決方案基於兩個想法:

  1. 捕捉鑰匙
  2. 用戶停止鍵入后,我們發送async POST請求。

對於我們的第一個目標,我們將使用addEventListener並偵聽keyup事件。 當用戶釋放鍵盤上的鍵時,會發生此事件。

對於第二個目標,我們需要捕獲上次keyup事件之間的時間,並將其與WAITING_TIME常量進行比較,例如500 ms。

另外,我們將使用async function聲明來定義fnFillGrid異步函數。 這將作為一個Promise返回一個AsyncFunction對象,該對象將使用async function返回的值進行解析,或者被async function內部拋出的未捕獲異常拒絕。 fnFillGrid也將實現fetch()方法,該方法使我們能夠發出類似於XMLHttpRequest網絡請求。 主要區別在於fetch()方法使用Promises ,它啟用了更簡單,更簡潔的API,避免了回調地獄,並且必須記住XMLHttpRequest的復雜API。

現在,我們可以調用await()運算符以等待響應Promise

這里有一個功能片段:

 const WAITING_TIME = 500; let startTime; let searchText = document.getElementById('search_input'); searchText.addEventListener('keyup', async(e) => { startTime = new Date().getTime(); setTimeout(async() => { let currentTime = new Date().getTime(); let timeDiff = currentTime - startTime; if (timeDiff >= WAITING_TIME) { const response = await fnFillGrid(searchText.value); console.log('response', response); } }, WAITING_TIME); }); async function fnFillGrid(message) { let result = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ query: message, }), headers: { "Content-type": "application/json; charset=UTF-8" } }); return result.json(); } 
 <form action="#"> Search: <input id="search_input" type="search" name="q"> </form> 

暫無
暫無

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

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