Home > Web Front-end > JS Tutorial > How Can I Persist Variables Across Page Loads in a Stateless HTTP Environment?

How Can I Persist Variables Across Page Loads in a Stateless HTTP Environment?

Barbara Streisand
Release: 2024-12-24 09:39:13
Original
387 people have browsed it

How Can I Persist Variables Across Page Loads in a Stateless HTTP Environment?

Persisting Variables Between Page Loads

HTTP being stateless, retaining values across page reloads requires external storage. Here's how to overcome this limitation:

Query String

On form submission via GET, the query string (?parameter=value) carries form field data. Set a hidden field's value accordingly:

<form method="GET">
    <input type="hidden" name="clicked" value="true" />
    <input type="submit" />
</form>
Copy after login

On page load, extract the query parameter:

function getParameterByName(name) {
    var regex = new RegExp("[\?&amp;]" + name + "=([^&amp;#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var clicked = getParameterByName('clicked');
Copy after login

Web Storage

HTML5 provides Web Storage, allowing for browser-based data storage. SessionStorage stores data only during the current browsing session:

sessionStorage.setItem('clicked', 'true');
Copy after login

On page load, retrieve the stored value:

var clicked = sessionStorage.getItem('clicked');
Copy after login

Cookies

Cookies are primarily used for server-side data storage but can also be leveraged for client-side storage. jQuery simplifies cookie management:

$.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
Copy after login

To read the cookie on page load:

var clicked = $.cookie('clicked');
Copy after login

Remember to un-set the cookie when no longer needed:

$.cookie('clicked', null);
Copy after login

Window.name

While not recommended, window.name can store strings across page refreshes and even domains:

window.name = "my value";
Copy after login

On page load, access the stored value:

var value = window.name;
Copy after login

The above is the detailed content of How Can I Persist Variables Across Page Loads in a Stateless HTTP Environment?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template