Refreshing a DIV element which has JSP code snippet inside

放肆的年华 提交于 2019-12-11 03:57:45

问题


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>
  // Loading 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.


回答1:


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



回答2:


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")) ; %>



回答3:


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



来源:https://stackoverflow.com/questions/4313203/refreshing-a-div-element-which-has-jsp-code-snippet-inside

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