使用Java、JSON、Ajax和HTML结合localStorage.setItem传递变量
Hey there! Let's put together a full solution to grab that JSON data from your Java backend via Ajax, store it in localStorage for cross-page access, and retrieve it whenever you need. Here's a step-by-step breakdown that works out of the box:
Your existing Java code is already doing the right things:
- You're populating a
Listwith all the necessary account group fields - Converting it to JSON using Gson
- Setting the correct
Content-Typeand UTF-8 encoding for the response
No changes needed here—this backend setup will serve the JSON data exactly as your frontend needs it.
We'll split this into two parts: a page that fetches the data and stores it in localStorage, and another page that retrieves and uses that stored data.
2.1 Page 1: Fetch JSON & Store in localStorage
This page will make an Ajax call to your backend, parse the response, and save it to localStorage. You can trigger this on a button click or automatically when the page loads.
Option A: Vanilla JavaScript (No Libraries)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Fetch & Store Data</title> </head> <body> <button id="saveDataBtn">Get Account Data & Save</button> <script> // Attach click handler to the button document.getElementById('saveDataBtn').addEventListener('click', fetchAndStoreData); // Or uncomment below to auto-run when the page loads // window.addEventListener('load', fetchAndStoreData); function fetchAndStoreData() { const xhr = new XMLHttpRequest(); // Replace '/your-backend-path' with your actual backend endpoint URL xhr.open('GET', '/your-backend-path', true); xhr.setRequestHeader('Accept', 'application/json'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { try { // Parse the JSON response into a JavaScript array const accountData = JSON.parse(xhr.responseText); console.log('Fetched data:', accountData); // Store the data in localStorage (must convert to string first) localStorage.setItem('accountGroupData', JSON.stringify(accountData)); alert('Data saved to localStorage successfully!'); } catch (err) { console.error('Failed to parse JSON:', err); alert('Error fetching data—check your backend endpoint.'); } } else { console.error('Request failed with status:', xhr.status); alert('Request failed. Please try again later.'); } }; xhr.onerror = function() { console.error('Network error occurred'); alert('Network connection issue. Please check your internet.'); }; xhr.send(); } </script> </body> </html>
Option B: Using jQuery (Simpler Syntax)
If you're already using jQuery in your project, here's a shorter version:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Fetch & Store Data (jQuery)</title> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> </head> <body> <button id="saveDataBtn">Get Account Data & Save</button> <script> $('#saveDataBtn').click(function() { $.ajax({ url: '/your-backend-path', type: 'GET', dataType: 'json', success: function(accountData) { console.log('Fetched data:', accountData); localStorage.setItem('accountGroupData', JSON.stringify(accountData)); alert('Data saved to localStorage successfully!'); }, error: function(xhr, status, err) { console.error('Request failed:', err); alert('Error fetching data—check your backend endpoint.'); } }); }); </script> </body> </html>
2.2 Page 2: Retrieve Data from localStorage
This page will pull the saved data from localStorage and display or use it as needed.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Retrieve Stored Data</title> </head> <body> <div id="dataContainer"></div> <script> window.addEventListener('load', function() { // Get the stored data from localStorage const storedData = localStorage.getItem('accountGroupData'); if (storedData) { try { // Convert the string back to a JavaScript array const accountData = JSON.parse(storedData); console.log('Retrieved data:', accountData); // Display the data on the page (customize this to your needs) const container = document.getElementById('dataContainer'); container.innerHTML = ` <h2>Account Group Data</h2> <ul> <li>Account ID: ${accountData[0]}</li> <li>Level: ${accountData[1]}</li> <li>Group Name: ${accountData[2]}</li> <li>Group Section: ${accountData[4]}</li> <li>Group NAS: ${accountData[5]}</li> <li>Next View: ${accountData[6]}</li> </ul> `; // You can also use the data in your application logic here // Example: Redirect based on nextView // window.location.href = accountData[6]; } catch (err) { console.error('Failed to parse stored data:', err); document.getElementById('dataContainer').textContent = 'Error loading saved data.'; } } else { document.getElementById('dataContainer').textContent = 'No data found in localStorage. Please visit the first page to fetch data.'; } }); </script> </body> </html>
- LocalStorage Limits: It only stores strings, so always use
JSON.stringify()when saving andJSON.parse()when retrieving arrays/objects. - CORS: If your frontend and backend are on different domains, you'll need to enable CORS in your Java backend (add
@CrossOriginto your controller method, for example). - Storage Persistence: Data in localStorage stays until the user clears their browser data or you call
localStorage.removeItem('accountGroupData')to delete it. - Size Limits: LocalStorage has a ~5MB limit, so avoid storing large datasets here.
内容的提问来源于stack exchange,提问作者Glyn

