JS新手求助:点击表单提交按钮导出数据为空问题
Hey there! Let's figure out why your CSV export is coming up empty—this is a super common mistake when you're starting out with JavaScript, so we'll get it fixed in no time.
The Root Cause
Right now, you're defining stockData the moment the page loads, before anyone has typed anything into the form fields. Those getElementById().value calls grab empty strings immediately, and even after a user enters data, stockData never updates because it only runs once at page initialization.
The Fix
We need to move the stockData collection logic inside your downloadCSV function, so it grabs the latest form values right when the user clicks to export. Here's the updated code, plus a working version of the convertArrayOfObjectsToCSV function (since you didn't include it, and it's critical for turning your data into valid CSV):
function downloadCSV(args) { // Grab form data RIGHT BEFORE exporting—this gets the latest user input var stockData = [ { Email: document.getElementById("email").value, Password: document.getElementById("pwd").value, Name: document.getElementById("name").value } ]; var data, filename, link; var csv = convertArrayOfObjectsToCSV({ data: stockData }); if (csv == null) return; filename = args.filename || 'export.csv'; if (!csv.match(/^data:text\/csv/i)) { csv = 'data:text/csv;charset=utf-8,' + csv; } data = encodeURI(csv); link = document.createElement('a'); link.setAttribute('href', data); link.setAttribute('download', filename); link.click(); } // Basic implementation of the CSV conversion function (if you don't have this already) function convertArrayOfObjectsToCSV(args) { var result, ctr, keys, columnDelimiter, lineDelimiter, data; data = args.data || null; if (data == null || !data.length) { return null; } columnDelimiter = args.columnDelimiter || ','; lineDelimiter = args.lineDelimiter || '\n'; // Get the keys from the first object to use as CSV headers keys = Object.keys(data[0]); result = ''; result += keys.join(columnDelimiter); result += lineDelimiter; // Loop through each object to add rows to the CSV data.forEach(function(item) { ctr = 0; keys.forEach(function(key) { if (ctr > 0) result += columnDelimiter; result += item[key]; ctr++; }); result += lineDelimiter; }); return result; }
Extra Checks to Ensure It Works
- Bind the function to your submit button: Make sure your form's button calls
downloadCSVwhen clicked. For example, in your HTML:
Or use unobtrusive JavaScript for better practice:<button onclick="downloadCSV({ filename: 'user-data.csv' })">Export Data</button>document.querySelector('#export-button').addEventListener('click', function() { downloadCSV({ filename: 'user-data.csv' }); }); - Test with real input: Type something into your email, password, and name fields, then click the export button—your CSV should now include the values you entered.
内容的提问来源于stack exchange,提问作者John

