带有ajax内容的页面不记得浏览器后退按钮后的状态

时间:2016-02-13 09:05:39

标签: javascript ajax jsp servlets history.js

我的网络应用非常简单

的servlet:

String greetings = "Hello from Servlet 1";
response.setContentType("text/plain");
response.getWriter().write(greetings);

jsp页面:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"
    type="text/javascript"></script>
<script src="js/jquery.history.js" type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
    <strong>Ajax Response</strong>:
    <div id="ajaxGetUserServletResponse"></div>
    <br>
    <button onclick="push1()">pushState 1</button>
    <p>
        <a href="help.html">help.html</a>
    </p>
</body>
</html>

APP-ajax.js:

function push1() {
    History.pushState({state:1,rand:Math.random()}, "State 1", "?state=1");
    $.get('servlet_1', {
    }, function(responseText) {
            $('#ajaxGetUserServletResponse').text(responseText);
    });
}

当我点击按钮时,我在jsp中回复了ajax内容,但是在我转到help.html页面并通过浏览器返回按钮返回后,jsp页面不记得最后一页状态(带有ajax内容) )。如何让jsp页面记住上次历史状态?

3 个答案:

答案 0 :(得分:0)

将ajax内容保存在localstorage或cookies中,然后在加载页面时设置条件。

答案 1 :(得分:0)

根据Nattu Raju的建议,localStorage可以帮助您查看this链接以了解如何实现此

你可以尝试这样的事情

&#13;
&#13;
var pageState
 = {};

function push1() {
    History.pushState({state:1,rand:Math.random()}, "State 1", "?state=1");
    $.get('servlet_1', {
    }, function(responseText) {
      var u ={}
      if(u == null){
      u.data = responseText;
        localStorage.setItem("pageState", u);
      }
            $('#ajaxGetUserServletResponse').text(responseText);
      
    });
}

after that you may get your data just by calling localStorage.getItem("pageState");
&#13;
&#13;
&#13;

答案 2 :(得分:0)

试试这个家伙

var pagestate = localStorage.getItem("pstate")

if(pagestate!=undefined || pagestate!=null){
   // so page having some state which is stored in localstorage
   // we have a pagestate in var pagestate
   // do changes based on pagestate variable
}
else
{
    // call server to fetch data and do other
    // save the pagestate as below
    localStorage.setItem("pstate", ajaxdata)
}