如何从同一列表取数并注入不同页面?关联两个Ajax请求的方法
Absolutely! You don’t have to duplicate your entire Ajax call across pages—instead, you can structure your code to reuse the data-fetching logic, and even cut down on redundant network requests if needed. Here are a few practical, actionable approaches tailored to your scenario:
1. Encapsulate a Reusable Data-Fetching Function
The cleanest way to share data access across pages is to extract your Ajax logic into a standalone function. This way, both pages call the same function to get the data, then handle rendering their unique UI styles independently.
Step 1: Create the Reusable Fetch Function
// Define this function in a shared JS file that both pages load function fetchPhishingData() { return new Promise((resolve, reject) => { $.ajax({ url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items", method: 'GET', headers: { 'Accept': 'application/json; odata=verbose' }, success: function(data) { resolve(data.d.results); // Pass back the raw items array for rendering }, error: function(error) { reject(`Error fetching phishing data: ${error}`); } }); }); }
Step 2: Use the Function on Your First Page (Original UI)
// On your first page, use the function to render your existing card layout fetchPhishingData() .then(items => { const phishingContainer = $('#phishing'); const start = Math.max(0, items.length - 4); // Show last 4 items for (let i = start; i < items.length; i++) { const phishingCard = ` <div class="col-sm-6 col-md-6 col-lg-3 mb-3"> <div style="background-color: #004685; height: 340px; position: relative;" class="card backImg2"> <div style="color: #fff;" class="card-body"> <h5 style="color: #ffe01a;" class="card-title">${items[i].Title}</h5> <p style="margin-bottom: -5px;" class="card-text">${items[i].Description}</p> <div style="width: 100%; margin: 0 auto; position: absolute; bottom: 0; right: 0" class="row"> <a style="background-color: #ffe01a!important; color: black!important; border: none; width: 100%;" href="${items[i].Image.Url}" class="btn btn-primary btn-sm" target="_blank"> More Info </a> </div> </div> </div> </div> `; phishingContainer.prepend(phishingCard); } }) .catch(error => console.log(error));
Step 3: Use the Same Function on Your Second Page (Alternate UI)
// On your second page, call the same function but render with your new styles fetchPhishingData() .then(items => { const alternateContainer = $('#phishing-alt-view'); // Unique container for your new layout items.forEach(item => { const altLayout = ` <div class="full-width-phishing-item p-4 border rounded mb-4"> <h2 class="text-primary mb-2">${item.Title}</h2> <p class="mb-3">${item.Description}</p> <a href="${item.Image.Url}" class="btn btn-secondary" target="_blank"> View Full Details </a> </div> `; alternateContainer.append(altLayout); }); }) .catch(error => console.log(error));
2. Add Caching to Avoid Redundant Requests
If users might navigate between both pages quickly, add browser caching to skip unnecessary API calls. This speeds up load times and reduces server load.
Updated Fetch Function with Cache
function fetchPhishingData(useCache = true) { return new Promise((resolve, reject) => { // Check for valid cached data first if (useCache) { const cachedData = localStorage.getItem('phishingExamplesData'); const expiryTime = localStorage.getItem('phishingDataExpiry'); if (cachedData && expiryTime && Date.now() < parseInt(expiryTime)) { resolve(JSON.parse(cachedData)); return; // Skip API call if cache is fresh } } // Fallback to API call if no valid cache $.ajax({ url: "/cyberSecurity/_api/web/lists/GetByTitle('phishingExamples')/items", method: 'GET', headers: { 'Accept': 'application/json; odata=verbose' }, success: function(data) { const items = data.d.results; // Cache data for 1 hour (adjust expiry as needed) localStorage.setItem('phishingExamplesData', JSON.stringify(items)); localStorage.setItem('phishingDataExpiry', Date.now() + 3600000); resolve(items); }, error: function(error) { reject(`Error fetching phishing data: ${error}`); } }); }); }
Key Takeaways
- Code Reusability: By separating data fetching from UI rendering, you only update your API logic once if the endpoint changes.
- Caching: Reduces network traffic and improves user experience, but always include an expiry to ensure users get fresh data when it updates.
- Separation of Concerns: Keeping fetch logic independent of rendering makes your code cleaner and easier to debug.
内容的提问来源于stack exchange,提问作者DigiDev

