You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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:

1. First: Confirm Your Backend Code Looks Good

Your existing Java code is already doing the right things:

  • You're populating a List with all the necessary account group fields
  • Converting it to JSON using Gson
  • Setting the correct Content-Type and UTF-8 encoding for the response

No changes needed here—this backend setup will serve the JSON data exactly as your frontend needs it.

2. Frontend Implementation: Full Code for Two Pages

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>
3. Key Notes to Avoid Issues
  • LocalStorage Limits: It only stores strings, so always use JSON.stringify() when saving and JSON.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 @CrossOrigin to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:01:10