programing

양식 데이터를 잃지 않고 현재 페이지를 다시로드하는 방법은 무엇입니까?

copyandpastes 2021. 1. 19. 08:19
반응형

양식 데이터를 잃지 않고 현재 페이지를 다시로드하는 방법은 무엇입니까?


양식 데이터를 잃지 않고 현재 페이지를 다시로드 할 수 있습니까? 내가 ..

window.location = window.location.href;

window.location.reload(true);

그러나이 두 가지는 나를 위해 이전 양식 데이터를 얻을 수 없습니다. 뭐가 잘못 되었 니 ? 브라우저를 수동으로 새로 고치면 괜찮습니다 (양식 데이터를 잃지 않습니다). 알아내는 방법을 알려주세요.

내 전체 코드는 다음과 같습니다.

<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>

그리고 내 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");
    });}

다양한 로컬 스토리지 메커니즘을 사용하여 Web Storage, IndexedDB, WebSQL (더 이상 사용되지 않음) 및 File API (더 이상 사용되지 않으며 Chrome에서만 사용 가능) (및 IE의 UserData)와 같은 브라우저에이 데이터를 저장할 수 있습니다.

가장 간단하고 널리 지원되는 WebStorage 는 브라우저를 닫을 때까지 메모리에 있는 영구 저장소 ( localStorage) 또는 세션 기반 ( sessionStorage) 이있는 WebStorage 입니다. 둘 다 동일한 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.

Use sessionStorage instead of localStorage if you want to store only temporary.


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

<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. Specially created for it.

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


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

works for me.


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. This is example code


As some answers mention, localStorage is 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.


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).


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


You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. 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.

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). 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. 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.


Register an event listener for keyup event:

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

ReferenceURL : https://stackoverflow.com/questions/17591447/how-to-reload-current-page-without-losing-any-form-data

반응형