Node.js(EJS模板):POST请求后如何保留下拉框选中值?
Got it, let's fix this so your form remembers the selected event type after the POST/redirect cycle. Here's a straightforward approach that works with your existing setup:
Step 1: Pass Filter Values Back to the Page on Redirect
When you handle the POST request, after processing the filter, you need to send the selected values back to the original page. The easiest way is to append them as query parameters to your redirect URL (or use a session if you don't want them visible in the URL).
Example Server-Side POST Handler:
const querystring = require('querystring'); // Built-in module, no need to install app.post('/your-form-endpoint', (req, res) => { // 1. Get the submitted filter value from the form const selectedEventType = req.body.constraints.eventType; // 2. Process your data filtering logic here... // 3. Redirect back to the original page, passing the filter as a query param // For multiple filters, use querystring.stringify to bundle all params const filterParams = { eventType: selectedEventType }; res.redirect(`/your-page-url?${querystring.stringify(filterParams)}`); });
Example Server-Side GET Handler (for the original page):
Now, when rendering the page, grab those query parameters and pass them to your EJS template:
app.get('/your-page-url', (req, res) => { // Get the filter values from the query string const filters = req.query; // Fetch your filtered events using these filters... const filteredEvents = /* your database/filter logic here */; // Pass both the events and filters to the template res.render('your-template-name', { events: filteredEvents, filters: filters }); });
Step 2: Update the EJS Template to Set Selected Options
Modify your <select> and <option> elements to check if the current filter value matches the option, and add the selected attribute if it does.
Updated EJS Code:
<div class="col-sm-6 g-mb-50"> <!-- Type --> <label class="g-font-weight-500 g-font-size-15 g-pl-30">Event Type</label> <select class="js-custom-select w-100 u-select-v2 u-shadow-v39 g-brd-main g-color-black g-bg-white text-left g-rounded-30 g-pl-30 g-py-12" data-placeholder="Type" data-open-icon="fa fa-angle-down" name="constraints[eventType]" data-close-icon="fa fa-angle-up"> <!-- Default to "All" if no filter is set --> <option <%= (!filters.eventType || filters.eventType === 'All') ? 'selected' : '' %>>All</option> <option <%= filters.eventType === 'Conference' ? 'selected' : '' %>>Conference</option> <option <%= filters.eventType === 'Field Trip' ? 'selected' : '' %>>Field Trip</option> <option <%= filters.eventType === 'ET Lab' ? 'selected' : '' %>>ET Lab</option> <option <%= filters.eventType === 'Special Event' ? 'selected' : '' %>>Special Event</option> </select> <!-- End Type --> </div>
Key Notes:
- If you prefer not to expose filters in the URL, use
req.sessionto store the filter values instead of query params. Just remember to clear the session when needed (like if the user resets the form). - Make sure the values in your
filters.eventTypematch exactly with the text in your<option>elements. If you addvalueattributes to your options (e.g.,<option value="conference">Conference</option>), adjust the condition to check against thevalueinstead of the displayed text. - Using
querystring.stringifyensures special characters in filter values are properly encoded, avoiding URL issues.
内容的提问来源于stack exchange,提问作者Arlind Bebja

