jQuery 如何在不丢失任何表单数据的情况下重新加载当前页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17591447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:22:08  来源:igfitidea点击:

How to reload current page without losing any form data?

javascriptjqueryhtmljquery-ui

提问by Cataclysm

Can I reload current page without losing any form data? I used..

我可以在不丢失任何表单数据的情况下重新加载当前页面吗?我用了..

window.location = window.location.href;

and

window.location.reload(true);

But these two things can't get earlier form datas for me. What is wrong ? When refresh browser manually, it is fine (I don't lose any form data). Please guide me how to figure it out.

但这两个东西无法为我获取更早的表单数据。怎么了 ?手动刷新浏览器时,没问题(我不会丢失任何表单数据)。请指导我如何弄清楚。

Here is my full code...

这是我的完整代码...

<div class="form-actions">
        <form>
            <table cellpadding = "5" cellspacing ="10">
                <tr class="control-group">
                    <td style="width: 100px;">
                        <div>Name:&nbsp;<font color="red">(*)</font></div>
                    </td>
                    <td>
                        <input type="text" id="inputName" placeholder="Name" required>
                    </td>
                </tr>
                <tr class="control-group">
                    <td>
                        <div>Email:&nbsp;<font color="red">(*)</font></div>
                    </td>
                    <td>
                        <input class="span3" placeholder="[email protected]" id= "inputEmail" type="email" required>
                    </td>
                </tr>
                <tr class="control-group">
                    <td>
                        <div>Phone:&nbsp;</div>
                    </td>
                    <td>
                        <input type="text" id="inputPhone" placeholder="phone number">
                    </td>
                </tr>
                <tr class="control-group">
                    <td>
                        <div>Subject:&nbsp;<font color="red">(*)</font></div>
                    </td>
                    <td>
                        <input type="text" id="inputSubject" placeholder="Subject" required>
                    </td>
                </tr>
                <tr class="control-group">
                    <td colspan ="2">
                        <div>
                            <div>Detail:&nbsp;</div>
                            <div class="controls">
                                <textarea id="inputDetail"></textarea>
                            </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                    <div>
                        <label style="font-weight: bold;" class="checkbox"> <input id="confirmCheck" value="" type="checkbox">
                                I Agree to the Personal information handling policy
                        </label>
                    </div>
                    <div id = "alert_placeholder"></div>
                        <div class="acceptment">
                            [Personal information handling policy]<br> <br>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div align="center">
                            <button id="btnConfirm" class="btn btn-primary">Confirm</button>
                            <input type="reset" style="width: 65px; height: 27px;" id="btnReset" class="btn">
                        </div>
                    </td>
                </tr>
            </table>
        </form>
    </div>

And at my JS file..

在我的 JS 文件中..

function bind() {
$('#btnConfirm').click(function(e) {
    if ($('#confirmCheck').is(":checked")) {
        getConfirmationForSendFAQ();
    }
    else {
        e.preventDefault();
        showalert("You should accept \"Personal Information Policy\" !", "alert-error");
    }
});};function getConfirmationForSendFAQ() {
    var name = $('#inputName').val();
    var email = $('#inputEmail').val();
    var phone = $('#inputPhone').val();
    var subject = $('#inputSubject').val();
    var detail = $('#inputDetail').val();

    $('.form-actions').empty();
    html = [];
    html.push("<table cellpadding ='8' class = 'submitInfo'");
    html.push("<tr>");
    html.push("<td class = 'title'>Name:</div>");
    html.push("<td class = 'value'>"+ name +"</td>");
    html.push("</tr>");

    html.push("<tr>");
    html.push("<td class = 'title'>Email Address:</div>");
    html.push("<td class = 'value'>"+ email +"</td>");
    html.push("</tr>");

    if (phone.trim().length > 0) {
        html.push("<tr>");
        html.push("<td class = 'title'>Phone No:</div>");
        html.push("<td class = 'value'>"+ phone +"</td>");
        html.push("</tr>");
    }

    html.push("<tr>");
    html.push("<td class = 'title'>Subject:</div>");
    html.push("<td class = 'value'>"+ subject +"</td>");
    html.push("</tr>");

    html.push("<tr>");
    html.push("<td class = 'title'>Detail Info:</div>");
    html.push("<td class = 'value'>"+ detail +"</td>");
    html.push("</tr>");

    html.push("<tr>");
    html.push("<td colspan='2'><div align = 'center'>");
    html.push("<button id='btnSend' class='btn btn-primary' style='width: 65px;'>Send</button>");
    html.push("<button id='btnReturn' class='btn btn-inverse' style='width: 65px; height: 27px; margin-left: 5px;'>Return</button>");
    html.push("</div></td></tr>");

    html.push("</table>");
    $('.form-actions').append(html.join(''));
    $('#btnReturn').click(function(e) {
        // HERE I WANT TO KNOW HOW TO DO.....
    });
    $('#btnSend').click(function(e) {
        alert("Doom");
    });}

回答by

You can use various local storage mechanisms to store this data in the browser such as Web Storage, IndexedDB, WebSQL (deprecated) and File API (deprecated and only available in Chrome) (and UserData with IE).

您可以使用各种本地存储机制将这些数据存储在浏览器中,例如 Web Storage、IndexedDB、WebSQL(已弃用)和 File API(已弃用且仅在 Chrome 中可用)(以及 UserData 与 IE)。

The simplest and most widely supported is WebStorage where you have persistent storage (localStorage) or session based (sessionStorage) which is in memory until you close the browser. Both share the same API.

最简单和最广泛支持的是 WebStorage,您可以在其中拥有持久性存储 ( localStorage) 或基于会话 ( sessionStorage) 的存储,直到您关闭浏览器为止。两者共享相同的 API。

You can for example (simplified) do something like this when the page is about to reload:

例如,当页面即将重新加载时,您可以(简化)执行以下操作:

window.onbeforeunload = function() {
    localStorage.setItem("name", $('#inputName').val());
    localStorage.setItem("email", $('#inputEmail').val());
    localStorage.setItem("phone", $('#inputPhone').val());
    localStorage.setItem("subject", $('#inputSubject').val());
    localStorage.setItem("detail", $('#inputDetail').val());
    // ...
}

Web Storage works synchronously so this maywork here. Optionally you can store the data for each blur event on the elements where the data is entered.

Web Storage 是同步工作的,所以这可以在这里工作。您可以选择将每个模糊事件的数据存储在输入数据的元素上。

At page load you can check:

在页面加载时,您可以检查:

window.onload = function() {

    var name = localStorage.getItem("name");
    if (name !== null) $('#inputName').val("name");

    // ...
}

getItemreturns nullif the data does not exist.

getItemnull如果数据不存在则返回。

Use sessionStorageinstead of localStorageif you want to store only temporary.

如果您只想临时存储,请使用sessionStorage代替localStorage

回答by Doug Wilhelm

I modified K3N's code to work for my purpose, and I added some comments to help others figure out how sessionStorage works.

我修改了 K3N 的代码以符合我的目的,并添加了一些注释以帮助其他人了解 sessionStorage 的工作原理。

<script>
    // Run on page load
    window.onload = function() {

        // If sessionStorage is storing default values (ex. name), exit the function and do not restore data
        if (sessionStorage.getItem('name') == "name") {
            return;
        }

        // If values are not blank, restore them to the fields
        var name = sessionStorage.getItem('name');
        if (name !== null) $('#inputName').val(name);

        var email = sessionStorage.getItem('email');
        if (email !== null) $('#inputEmail').val(email);

        var subject= sessionStorage.getItem('subject');
        if (subject!== null) $('#inputSubject').val(subject);

        var message= sessionStorage.getItem('message');
        if (message!== null) $('#inputMessage').val(message);
    }

    // Before refreshing the page, save the form data to sessionStorage
    window.onbeforeunload = function() {
        sessionStorage.setItem("name", $('#inputName').val());
        sessionStorage.setItem("email", $('#inputEmail').val());
        sessionStorage.setItem("subject", $('#inputSubject').val());
        sessionStorage.setItem("message", $('#inputMessage').val());
    }
</script>

回答by Rajan Rawal

Find this on GitHub. Specially created for it.

在 GitHub 上找到这个。专为它打造。

https://gist.github.com/zaus/4717416

https://gist.github.com/zaus/4717416

回答by Julian K

This answer was extremely helpful to me, and saves the trouble of going through each field manually:

这个答案对我非常有帮助,省去了手动浏览每个字段的麻烦:

Using jQuery to store the state of a complicated form

使用 jQuery 存储复杂表单的状态

回答by Naveen Agarwal

window.location.reload() // without passing true as argument

works for me.

为我工作。

回答by moutonjr

I usually submit automatically my own form to the server and reload the page with filled arguments. Replace the placeholder arguments with the params your server received.

我通常会自动将我自己的表单提交到服务器并使用填充的参数重新加载页面。用您的服务器收到的参数替换占位符参数。

回答by dikkini

Agree with HTML5 LocaStorage. This is example code

同意 HTML5 LocaStorage。 这是示例代码

回答by nickytonline

As some answers mention, localStorageis a good option and you can certainly do it yourself, but if you're looking for a polished option, there is already a project on GitHub that does this called garlic.js.

正如一些答案所提到的,localStorage是一个不错的选择,你当然可以自己做,但如果你正在寻找一个完美的选择,GitHub 上已经有一个名为大蒜.js 的项目

回答by Dileep

You have to submit data and reload page (server side render form with data), just reloading will not preserve data. It is just your browser might be caching form data on manual refresh (not same across browsers).

您必须提交数据并重新加载页面(带有数据的服务器端渲染表单),仅重新加载不会保留数据。只是您的浏览器可能会在手动刷新时缓存表单数据(不同浏览器不同)。

回答by paka

You can use localStorage ( http://www.w3schools.com/html/html5_webstorage.asp) to save values before refreshing the page.

您可以使用 localStorage ( http://www.w3schools.com/html/html5_webstorage.asp) 在刷新页面之前保存值。