javaScript在表單提交時獲取表單數據的示例代碼
方法 1:使用 FormData
對象
FormData
是一個方便的內置對象,用于獲取表單中的鍵值對數據。
示例代碼
<form id="myForm"> <input type="text" name="username" value="JohnDoe" /> <input type="email" name="email" value="john@example.com" /> <input type="password" name="password" value="12345" /> <button type="submit">Submit</button> </form> <script> document.getElementById('myForm').addEventListener('submit', function (event) { event.preventDefault(); // 阻止默認表單提交行為 // 獲取表單數據 const formData = new FormData(this); // 遍歷表單數據 for (let [key, value] of formData.entries()) { console.log(`${key}: ${value}`); } // 如果需要轉換為 JSON 對象 const data = Object.fromEntries(formData.entries()); console.log(data); }); </script>
解釋:
FormData(this)
:創(chuàng)建一個包含表單所有數據的對象。formData.entries()
:獲取鍵值對的迭代器。Object.fromEntries()
:將鍵值對轉換為對象。
方法 2:通過 serialize
手動提取表單數據
可以通過直接訪問表單元素的值手動提取表單數據。
示例代碼
<form id="myForm"> <input type="text" name="username" value="JohnDoe" /> <input type="email" name="email" value="john@example.com" /> <input type="password" name="password" value="12345" /> <button type="submit">Submit</button> </form> <script> document.getElementById('myForm').addEventListener('submit', function (event) { event.preventDefault(); const form = event.target; const formData = {}; // 遍歷表單元素 Array.from(form.elements).forEach((element) => { if (element.name) { formData[element.name] = element.value; // 獲取每個字段的值 } }); console.log(formData); }); </script>
解釋
form.elements
:獲取表單中所有的控件(如<input>
、<select>
等)。- 通過
element.name
識別表單字段并提取其value
。
方法 3:使用 querySelector
手動獲取單個字段數據
如果你只想獲取某幾個字段的數據,可以直接用選擇器獲取特定的表單字段。
示例代碼
<form id="myForm"> <input type="text" id="username" name="username" value="JohnDoe" /> <input type="email" id="email" name="email" value="john@example.com" /> <button type="submit">Submit</button> </form> <script> document.getElementById('myForm').addEventListener('submit', function (event) { event.preventDefault(); // 獲取單個字段值 const username = document.querySelector('#username').value; const email = document.querySelector('#email').value; console.log(`Username: ${username}`); console.log(`Email: ${email}`); }); </script>
解釋
- 通過
querySelector
獲取具體字段,并訪問其value
。
方法 4:通過 URL 查詢參數形式獲取表單數據
可以將表單提交后的數據序列化成 URL 查詢字符串的形式。
示例代碼
<form id="myForm"> <input type="text" name="username" value="JohnDoe" /> <input type="email" name="email" value="john@example.com" /> <button type="submit">Submit</button> </form> <script> document.getElementById('myForm').addEventListener('submit', function (event) { event.preventDefault(); const formData = new FormData(this); // 轉換為 URL 查詢參數 const queryString = new URLSearchParams(formData).toString(); console.log(queryString); // username=JohnDoe&email=john%40example.com }); </script>
解釋
URLSearchParams(formData)
:將表單數據轉換為查詢參數格式。.toString()
:生成 URL 查詢字符串。
方法 5:配合 AJAX 提交表單數據
通過 fetch
或 XMLHttpRequest
可以將表單數據異步提交到服務器。
示例代碼
<form id="myForm"> <input type="text" name="username" value="JohnDoe" /> <input type="email" name="email" value="john@example.com" /> <button type="submit">Submit</button> </form> <script> document.getElementById('myForm').addEventListener('submit', function (event) { event.preventDefault(); const formData = new FormData(this); // 提交表單數據到服務器 fetch('/submit', { method: 'POST', body: formData, }) .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error('Error:', error)); }); </script>
解釋
fetch('/submit', { method: 'POST', body: formData })
:將表單數據發(fā)送到服務器。- 響應結果可以通過
response.json()
處理。
總結
- 簡單提取數據:使用
FormData
。 - 手動提取數據:直接訪問
form.elements
或querySelector
。 - 序列化為查詢字符串:通過
URLSearchParams
。 - 配合提交到服務器:結合
fetch
或其他 AJAX 方法實現動態(tài)提交。
選擇方法取決于實際需求,例如是否需要動態(tài)處理、是否需要提交到服務器等。
到此這篇關于javaScript如何在表單提交的時候獲取到表單數據的文章就介紹到這了,更多相關javaScript表單提交獲取表單數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!