开发者

Refreshing a DIV element which has JSP code snippet inside

I have a JSP page where I am reading Session Attributes that I set in the Session.

I want to read the Session attributes in regular intervals. I don't want to reload the whole page instead I am just keeping my JSP Session read attributes in my DIV and trying to reload the DIV. But it is not reloading the DIV.

Here is my code base:

<html>
  <head>
  // Load开发者_运维技巧ing CSS and Script files
  </head>
  <body>
    <div id="loadData" style='display:none;'>
         <% 
           String strStatus = String.valueOf(session.getAttribute("Status")) ;
          %>
    </div>
  </body>
  <script type="text/javascript">
    var reqStatus = '<%= strStatus %>';

    $(this).load(function(){
       setInterval(function() {
            $("#loadData").load();
          } ,1000);
     });
     $("#loadData").load(function(){
        if(reqStatus == 'Done') {
        // My Code goes here..
        }
     });
</html>

Any better ideas are also welcome.


JSP renders once, on the server, and is then sent to the client, after which the Java code does nothing. You can't put both the HTML/javascript code and the Java code in the same file if you want them to be loaded at different times / frequencies.

Put this into a separate .jsp file:

<%= String.valueOf(session.getAttribute("Status")) ; %>

Assume it's mapped to some url /checkStatus.jsp

Remove the loadData div because you don't need it anymore. Replace your javascript with:

var reloadStatus = function () {
    $.ajax("/checkStatus.jsp", function (data) {
        if (data == "Done") {
            // Your code here
        }
    });
};

setInterval(reloadStatus, 1000);


Your JSP code is evaluated only once -- when the page first loads. When JSP code runs, HTML is generated and sent to the browser. You cannot "reload" a div like that; the JSP code will not run.

What you can do is put the JSP code into a separate filee and then use jQuery.load to load that page into a div:

jQuery(document).ready(function() {
   setInterval(function() {
       jQuery('#loadData').load('/status.jsp');
   }, 1000);
}

status.jsp will contain just the one line:

<%= String.valueOf(session.getAttribute("Status")) ; %>


The code in a JSP is compiled/executed before the resulting HTML is sent to the browser. You can't reload part of the page as-rendered and expect it to change. You would probably need to make a hidden iframe and reload that completely (easy), or make a webservice to query the params (harder).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜