简体   繁体   English

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

[英]How to reload current page without losing any form data?

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="user@gmail.com" 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");
    });}

You can use various local storage mechanisms to store this data in the browser such as the Web Storage API , IndexedDB and WebSQL (deprecated) (and UserData with IE).您可以使用各种本地存储机制将这些数据存储在浏览器中,例如Web Storage APIIndexedDB和 WebSQL(已弃用)(以及带有 IE 的 UserData)。

The simplest and most widely supported is Web Storage where you have persistent storage ( localStorage ) or session based ( sessionStorage ) which is in memory until you close the browser.最简单和最广泛支持的是 Web 存储,其中您有持久存储 ( localStorage ) 或基于会话的 ( sessionStorage ),它在内存中直到您关闭浏览器。 Both share the same API.两者共享相同的 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 may work here.网络存储同步工作,所以这可能在这里工作。 Optionally you can store the data for each blur event on the elements where the data is entered.或者,您可以将每个模糊事件的数据存储在输入数据的元素上。

At page load you can check:在页面加载时,您可以检查:

window.onload = function() {

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

    // ...
}

getItem returns null if the data does not exist.如果数据不存在, getItem返回null

Replace " localStorage " with " sessionStorage " in the code above if you want to store data only temporary.如果您只想临时存储数据,请将上面代码中的“ localStorage ”替换为“ sessionStorage ”。

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>

Find this on GitHub.在 GitHub 上找到这个。 Specially created for it.专门为它打造的。

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

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存储复杂表单的状态

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

为我工作。

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

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.将占位符参数替换为您的服务器收到的参数。

Agree with HTML5 LocaStorage.同意 HTML5 LocaStorage。 This is example code这是示例代码

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).只是您的浏览器可能会在手动刷新时缓存表单数据(跨浏览器不一样)。

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

You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage.您可以使用我编写的库FormPersistence.js ,它通过将值保存到本地/会话存储来处理表单(反)序列化。 This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.这种方法类似于另一个答案中链接的方法,但它不需要 jQuery,也不会将明文密码保存到网络存储中。

let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)

The optional second parameter of each FormPersistence function defines whether to use local storage ( false ) or session storage ( true ).每个FormPersistence函数的可选第二个参数定义是使用本地存储 ( false ) 还是会话存储 ( true )。 In your case, session storage is likely more appropriate.在您的情况下,会话存储可能更合适。

The form data by default will be cleared from storage upon submission, unless you pass false as the third parameter.默认情况下,表单数据将在提交时从存储中清除,除非您将false作为第三个参数传递。 If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter.如果您有特殊的值处理功能(例如插入元素),那么您可以将它们作为第四个参数传递。 See the repository for complete documentation.有关完整文档,请参阅存储库。

A simple and generic (no jquery) solution for all input (type text) fields unsing the local storage.一个简单而通用的(无 jquery)解决方案,用于所有输入(类型文本)字段,取消本地存储。

function save_data(){
    let fields = document.querySelectorAll("input[type='text']")
    let saved_fields = []
    fields.forEach(x => {
        saved_fields.push({
            key: x.id,
            value: x.value
        })
    })
    localStorage.setItem("saved_data", JSON.stringify(saved_fields))
 }

 function show_saved_data(){
     JSON.parse(localStorage.getItem("saved_data")).forEach(x => {
         document.getElementById(x.key).value = x.value
     })
 }

if you want to include "select/checkboxes" fields etc. you would have to add some if else logic in the for loop and change the query....如果要包含“选择/复选框”字段等,则必须在 for 循环中添加一些 if else 逻辑并更改查询....

Use $_POST itself:使用 $_POST 本身:

<?php           
isset($_POST['value']) ? $value= $_POST['value'] : $value= NULL;
echo '<form method="POST">';
echo '<input type="text" name="value" value="'.$value.'"/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
?>

Register an event listener for keyup event:keyup事件注册一个事件监听器:

document.getElementById("input").addEventListener("keyup", function(e){
  var someVarName = input.value;
  sessionStorage.setItem("someVarKey", someVarName);
  input.value = sessionStorage.getItem("someVarKey");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不丢失任何数据的情况下重新加载页面 - How to reload page without losing any data 如何在不丢失任何插入(div)数据的情况下重新加载页面 - How to reload page without losing any inserted (div) data 如何重新加载当前页面而不丢失javascript中的任何数据,它在chrome上有效,但在Safari中无法正常工作 - how to reload current page without losing any data in javascript its worked me on chrome but couldn't worked in safari 如何在不丢失添加的列表项的情况下重新加载当前页面? - How to reload current page without losing added list items? 重新加载当前页面而不会丢失用户输入 - Reload current page without losing of user input 如何在不丢失变量值的情况下重新加载页面 - How to reload the page without losing variables value 如何在不丢失任何数据的情况下防止双重表单提交? - How to prevent double form submit without losing any data? 重新加载父Shadowbox iframe页面而不会丢失POST数据 - Reload parent shadowbox iframe page without losing POST data 将表单数据保存在url中,而无需重新加载页面 - Save form data in the url without page reload 在刷新页面丢失数据 - 任何没有 localstorage 的解决方案 - losing data in refresh page - any solution without localstorage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM