实现追踪号码字段搜索跳转至对应文件的技术求助
Solution for Tracking Number Redirect
Here's how to implement the automatic redirect based on the entered tracking number:
Step 1: Update the HTML Form
Add id attributes to the form and input field to simplify JavaScript targeting, and set the button's type to submit:
<form id="trackingForm" class=""> <div class="col-md-7 col-sm-7"> <div class="form-group"> <input type="text" id="trackingNumber" placeholder="Enter your product ID" required="" class="form-control box-shadow"> </div> </div> <div class="col-md-5 col-sm-5"> <div class="form-group"> <button type="submit" class="btn-1">track your product</button> </div> </div> </form>
Step 2: Add JavaScript for Redirect Logic
Insert this script at the end of your HTML document (right before </body>) to handle form submission and redirect:
Basic Version (Single Extension)
Use this if all your tracking files use the same extension (either .php or .html):
document.getElementById('trackingForm').addEventListener('submit', function(e) { e.preventDefault(); // Stop default form submission const trackingId = document.getElementById('trackingNumber').value.trim(); // Validate input if (!trackingId) { alert('Please enter a valid product ID'); return; } // Adjust the extension and path as needed const targetFile = `${trackingId}.php`; // Replace with .html if your files use that extension // Redirect to the target file window.location.href = targetFile; });
Advanced Version (Check Both Extensions)
If your tracking files mix .php and .html formats, use this version to automatically detect which file exists:
document.getElementById('trackingForm').addEventListener('submit', async function(e) { e.preventDefault(); const trackingId = document.getElementById('trackingNumber').value.trim(); if (!trackingId) { alert('Please enter a valid product ID'); return; } const phpPath = `${trackingId}.php`; const htmlPath = `${trackingId}.html`; // Check if PHP file exists try { const phpCheck = await fetch(phpPath, { method: 'HEAD' }); if (phpCheck.ok) { window.location.href = phpPath; return; } } catch {} // Check if HTML file exists try { const htmlCheck = await fetch(htmlPath, { method: 'HEAD' }); if (htmlCheck.ok) { window.location.href = htmlPath; return; } } catch {} // If neither file exists alert('No tracking record found for the entered ID'); });
Key Notes
- File Path: Ensure your tracking files (e.g.,
112233.php) are stored in the same directory astracking.html. If they're in a subfolder, update the path (e.g.,./tracking-files/${trackingId}.php). - Validation: The
requiredattribute on the input already enforces non-empty entries, but the JavaScript adds an extra alert for clarity. - HEAD Request: The advanced version uses a
HEADrequest to check file existence without downloading the entire file, which is efficient.
内容的提问来源于stack exchange,提问作者jessica martin
相关产品推荐
相关产品推荐

