views:

325

answers:

1

I need to use ajax feature to load an external div element (an external jsp file) into the current page. That JSP page contains a dynamic content - e.g. content that is based on values received from the current session.

I solved this problem somehow, but I'm in doubt because I think that my solution is bad , or maybe there is better solution since I'm not expert.

I have three files:

  • Javascript function that is triggered when a TR element is clicked, it requests html data from a servlet:

    $("#inboxtable tbody tr").click(function(){
    
    
    
    var trID = $(this).attr('id');
    $.post("event?view=read",{id:trID}, function(data){
        $("#eventContent").html(data); // load external file
    },"html"); // type
    
    });
  • The servlet "event" loads the data and generates HTML content using include method :

    String id = request.getParameter("id");
    if (id != null) {
       v.add("Test");
       v.add(id);
       session.setAttribute("readMessageVector", v);
       request.getRequestDispatcher("readMessage.jsp").include(request, response);
    }
    
  • Finally: The external readMessage jsp file looks like this:

    <p>
       Text: ${readMessageVector[0]}
    </p>
    <p>
       ID:   ${readMessageVector[1]}
    </p>
    

    My questions

  • Is this solution good enough to solve this problem - loading external jsp that has dynamic content ?

  • Is there a better solution ? such as putting all DIVs elements in the same file instead of loading them from an external file , and showing or hiding those elements using javascript/jquery in the same file ? In this way , I will only use the JSON ?

+1  A: 

This solution seems fine to me. If you start to make lots of different AJAX calls in the future, you would be better returning a lightweight response such as JSON from the jsps - this will save bandwidth and jQuery can be used to generate the bulky HTML markup.

Finbarr
Thanks @Finbarr, but if I return JSON , I think it is difficult to build the HTML elements dynamically.am I right ? what about showing and hiding DIV elements in the same file instead of loading external divs?
BugKiller
Building the HTML elements dynamically is very easy. Typically, with jQuery, something like $('<div></div>').insertAfter() or .insertBefore() or .appendTo() or .prependTo(), and you can chain up the method calls to add your content inside the div before it is inserted.
Finbarr