首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

jQuery AJAX serialize() 實現表單數據自動序列化傳遞 PHP 處理

     編輯:程式設計疑難解答

痛點

手動 getElementById 逐個取值,字段多時極其繁瑣且易漏。

jQuery 一鍵序列化

<form id="frmSubmit">
    <input name="username" type="text" />
    <input name="password" type="password" />
    <select name="role"><option value="1">Admin</option></select>
    <textarea name="remark"></textarea>
    <button type="submit">提交</button>
</form>

<script>
$('#frmSubmit').on('submit', function(e) {
    e.preventDefault(); // 阻止默認提交
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: $(this).serialize(), // 自動序列化為 username=xxx&password=yyy&role=1&remark=zzz
        dataType: 'json',
        success: function(resp) {
            alert(resp.message);
        }
    });
});
</script>

PHP 端接收完全相容

<?php
// process.php
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$role = $_POST['role'] ?? '';
$remark = $_POST['remark'] ?? '';

// 業務邏輯...
echo json_encode(['success' => true, 'message' => '儲存成功']);
?>

進階:FormData 支援檔案上傳

data: new FormData(this), // 包含檔案輸入
processData: false,
contentType: false,

serialize() 不包含檔案,需用 FormData。

原生 JS 替代 (無 jQuery)

const form = document.getElementById('frmSubmit');
form.addEventListener('submit', async e => {
    e.preventDefault();
    const data = new URLSearchParams(new FormData(form)).toString();
    const resp = await fetch('process.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: data
    });
    const json = await resp.json();
    alert(json.message);
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved