使用FormData遇Safari不支持,寻求最优替代解决方案
Hey there! I totally get how frustrating it is when Safari doesn't support an API you're relying on. Let's replace that FormData usage with a manual approach that does exactly what your original code was doing—collecting form field values into a plain object.
Core Idea
Instead of relying on FormData, we'll directly iterate over all the form's elements, filter out irrelevant ones, and build our key-value object manually. This replicates the behavior of your data.forEach loop without needing the FormData API.
Updated Code
Here's a drop-in replacement for your existing code, with fixes for edge cases (like uninitialized obj and handling different input types):
let form = document.querySelector('form'); form.addEventListener('submit', e => { e.preventDefault(); // Don't forget to stop the default form submission let obj = {}; // Initialize the object (your original code missed this, which would cause errors) // Convert form.elements to an array and loop through each control Array.from(form.elements).forEach(element => { // Skip disabled elements, submit/reset buttons, and unchecked radios/checkboxes if (element.disabled) return; switch(element.type) { case 'submit': case 'reset': case 'button': return; // Ignore these button types case 'checkbox': case 'radio': if (!element.checked) return; // Only include checked options break; } // Handle select elements specifically (though their value works like inputs too) if (element.tagName === 'SELECT') { obj[element.name] = element.value; return; } // For all other valid controls (text inputs, textareas, etc.), grab the value obj[element.name] = element.value; }); // Now `obj` has the same structure as what you got from FormData console.log(obj); // Add your logic to send this data (e.g., fetch request) here });
Key Notes
- Initializing
obj: Your original code didn't initializeobjbefore assigning properties, which would throw an error. We fixed that here. - Handling Edge Cases: We skip disabled elements, submit/reset buttons, and only include checked checkboxes/radios—just like
FormDatadoes. - File Uploads: If your form includes file inputs, this approach won't handle file objects (since
FormDatahandles that natively). If you need file support, you'd need to add extra logic to read file data, but that's a more complex edge case. For standard text/select inputs, this works perfectly.
Why This Works
This method mimics the default behavior of FormData by only including valid, user-interacted form controls. It's fully compatible with older Safari versions and gives you full control over how data is collected.
内容的提问来源于stack exchange,提问作者Taylor Austin

