Use the back button with an AJAX form?

Hello,

I have an ASP.NET MVC page containing 5 cascading drop-down lists (hidden until loading). When the first is installed, AJAX will retrieve data for the second drop-down list (dynamic html).

If we go to the next page and then click the back button in the browser, only the first cascading drop-down list will be displayed, even if we set all 5?

Note. By setting the correct sequence of requests, the service can set up the form in the same way as if using Ajax, but the service is never projected using the back button.

Request for advice

+4
source share
1 answer

You need the HTML 5 History API. You can read about it in many places, for example here .

Here is a simple example, only HTML (your whole problem is not with ASP.NET MVC, but with HTML, this can happen on any platform):

Let's say you have page 1 (index.html):

<!DOCTYPE html> <html> <head> <title>Test</title> <meta charset="utf-8" /> </head> <body> <input type="text" id="txt1" /> <br /> <input type="text" id="txt2" /> <br /> <br /> <button onclick="doStuff();">do stuff</button> <button onclick="goFurther();">go further</button> <script type="text/javascript"> var qs = (function (a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p = a[i].split('=', 2); if (p.length == 1) b[p[0]] = ""; else b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return b; })(window.location.search.substr(1).split('&')); window.onload = function () { var data1 = qs["txt1"]; var data2 = qs["txt2"]; if (data1 == undefined) data1 = ""; if (data2 == undefined) data2 = ""; var textbox1 = document.getElementById("txt1"); var textbox2 = document.getElementById("txt2"); textbox1.value = data1; textbox2.value = data2; } function doStuff() { var textbox1 = document.getElementById("txt1"); var textbox2 = document.getElementById("txt2"); history.pushState('abc', 'title', 'index.html?txt1=' + textbox1.value + "&txt2=" + textbox2.value); } function goFurther() { window.location = "/next.html"; } </script> </body> </html> 

As you can see (and try in the project), the first button takes data in two fields (text fields in my overly simplified example) and sets the current URL to one using a query string containing this data (again, being too simplistic example, it does not perform validation, escaping, encoding, etc.).

The second button takes you to another page:

 <!DOCTYPE html> <html> <head> <title>Next crp</title> <meta charset="utf-8" /> </head> <body> asdf </body> </html> 

Here you can only go to it. Going to the first page (clicking the "Back" button in the browser) will lead you to the URL that was configured using javascript using the request button.

The onload handler will re-populate the elements with data in the request.

Be sure to find online resources about the "HTML5 History API".

I hope this example helps.

0
source

Source: https://habr.com/ru/post/1336426/


All Articles