Back Button Handle A Dynamic Form

我们两清 提交于 2019-12-30 00:31:04

问题


I have a form with an array of text fields. The user (through javascript) can add an arbitrary number of text fields to the form. After submitting the form and pressing the back button the form displays only with the fields that were on the original form when it was first rendered (any added text fields are lost). What is the best way to allow the back button to render the form in the state when the user submitted it? Any ideas are welcome, some things I've tried are:

  • Put the form data in a cookie (this doesn't work great for a couple reasons but the biggest killer for me is that cookies are limited to 4K in size)
  • Put the form data in a session
  • Submit the form via AJAX and then manage the history

Thanks for the help. I've posted a test form on my website at http://fishtale.org/formtest/f1.php. Also here is a simple form exhibiting the behavior I mentioned:

<form action="f2.php" method="post">
<input type="text" name="text[]" id="text1"/>
<input type="submit" name="saveaction" value="submit form" />
</form>

<a href="f2.php" id="add_element">Add Form Element</a>

<script type="text/javascript" 
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" ></script>

<script type="text/javascript" >
    $('#add_element').click(function (event) {
        event.preventDefault();
        $('#text1').after('<input type="text" name="text[]" />');
    });
</script>

This is similar to a question I posted a while ago, Best Way For Back Button To Leave Form Data, however, this form's elements are modified by the user.


回答1:


I can't find a prewritten library for this, but I'm sure its been solved before. If I had to it myself I would take this approach:

  1. Use the command pattern so that each method which modifies the page's UI by adding controls also invokes an AJAX method to push the method invoked (textual Javascript representation) onto a queue stored in the server's session.

  2. After body onLoad completes, use an AJAX method to query the server's session for a command queue for the page the user is on. If one is retrieved, just eval each member of the queue to rebuild the page's UI in the same order the user did it.

Keep in mind with this approach you are recording not just additions of controls, but removals as well. You will require separate state holders for user input controls, like text boxes (you will also likely need server-side session with AJAX method access).




回答2:


How about creating an <input type="hidden"> (with no name or outside the form so it's not submitted) in which you store an encoded list of extra fields to add and their values? While the browser won't remember newly-added fields on ‘back’, it will remember the values of hidden fields that were in the form from the start.

Here's an example that saves the extra fields on document unload and retrieves them on ready:

<input type="hidden" id="remembertexts" />

<form action="http://www.google.com/" method="get">
    <div id="texts">
        <input type="text" name="text[]" value="" />
    </div>
    <div>
        <input type="submit" />
        <input type="button" id="addtext" value="+" />
    </div>
</form>

<script type="text/javascript">

    // Add new field on button press
    //
    $('#addtext').click(function() {
        addInput('');
    });

    function addInput(text) {
        $('#texts input').eq(0).clone().val(text).appendTo('#texts');
    };

    // Store dynamic values in hidden field on leaving
    //
    $(window).bind('beforeunload', function() {
        var vals= [];
        $('#texts input').each(function() {
            vals.push(encodeURIComponent(this.value));
        });
        $('#remembertexts').val(vals.join(';'));
    });

    // Retrieve dynamic values on returning to page
    //
    $(function() {
        var extratexts= $('#remembertexts').val().split(';').slice(1);
        $.each(extratexts, function() {
            addInput(decodeURIComponent(this));
        });
    });
</script>

Notes:

  • You can use form.onsubmit instead of window.onbeforeunload if you only need it to remember values over a submission. onunload doesn't work as some browsers will already have stored the old form values before that event occurs.

  • In Firefox the position of the hidden input is important. For some reason, if you put it below the dynamically-added fields, Firefox gets confused about which input it is and fails to remember the value.

  • This example doesn't work in Opera. It can be made to work in Opera, but it's a pain. Opera's calling of load and unload events is inconsistent so you have to use onsubmit instead, or setting the hidden field on a polling interval, or something. Worse, when Opera remembers previous form-field values, it actually doesn't fill them in until after onload has fired! This already causes many, many form-scripting problems. You can work around that by putting a small timeout in your onload to wait until the form values have gone in if you need Opera compatibility.




回答3:


In good browsers you can have it working perfectly simply by not breaking it.

Firefox 1.5 uses in-memory caching for entire Web pages, including their JavaScript states, for a single browser session. Going backward and forward between visited pages requires no page loading and the JavaScript states are preserved. source

This is supported in Opera and WebKit too. However DOM cache is only possible in you stick to the rules:

  1. Don't use onunload, onbeforeunload.
  2. Don't use Cache-control: no-store or must-revalidate.
    In PHP you must change session.cache_limiter from patently_ridiculous (I think they spell it nocache) to none.

    session_cache_limiter('none');
    
  3. Unfortunately HTTPS is also out.

If you don't force browsers to reload the page, they won't. They'll keep the DOM and its values unchanged, exactly as RFC 2616 suggests.


However, if you're looking for place to stash the data, there's incredibly clever hack – window.name can store megabytes of data. It's not sent to server, and it isn't shared between windows.

There are also Flash cookies and HTML 5 localStorage is implemented in IE8 and Safari 4.




回答4:


Step 2: The script processing the form puts the values entered into an array and stores that array into a session variable (or text / db / whatever you find appropriate).

Step 1: The script which outputs the form adds a javascript (which in turn fills in the form) if that session variable is found (and it also clears the session variable).




回答5:


You could make your own back button at the top of the web page and make it bigger and prettier than the standard web browser back button.

Under the hood your code could know what the previous state was and revert to it or if there was no previous state you can maybe call the browser's back function?




回答6:


Block the use of the back button. When the back button is pressed, rerender the previous page for the user with the new fields included, either visibly if that makes sense, or hidden. That way the user is able to use the back button normally and you have full control over the appearance of the ''previous'' page.

In your specific use case, you just need to render the page with all the fields visible and filled in with the values that were submitted.

This is a good pattern to follow for any wizard type of process where you provide a sequence of forms for the user to fill in and they may choose to go back to a previous form.

To make it perfectly clear, I am suggesting that you use this advice on capturing the onUnload event to trigger form submission (so that you get the entered values) and to rerender the previous page that "back" would have displayed (without the values). The only alternative is to use Ajax to send the entered values every time that the user leaves a field, and then have every page check with the server via AJAX to retrieve additional values to display.

Here are some additional pages that discuss taking control over the function of the back button and using the unload event to persist forms data:

  • Mastering the Back Button with Javascript
  • Don't Let the Door Hit You
  • Cross Browser unload Event and the Back Button
  • Persisting portlet forms data in WebSphere Portal V5.1


来源:https://stackoverflow.com/questions/1724739/back-button-handle-a-dynamic-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!