Search code examples
javajqueryajaxstruts-1

Display page data on same page without forwarding it to another page


In my webpage (Eg Link1: http://localhost:8086/MyStrutsApp/login.do) I have several links. When a user clicks on one of the links, he is taken to another page (Eg link2: http://localhost:8086/MyStrutsApp/AddBook.jsp) to fill an html form.

Now what I want to achieve is that when any user clicks on the link, that html form (Link2) is displayed on the same page (i.e. Link1).

I have no idea how to achieve this.


Solution

  • The AJAX way to achieve this is the following:

    • you have a DIV on your original page that will be replaced (i.e., either has content that only makes sense in the original context or completely empty)
    • your Link2 servlet produces only the contents of the above DIV (and not the contents of that page)
    • you use a tiny bit of Javascript to make an AJAX call and fill the DIV with the response.

    If you want to use Dojo, the HTML page would look like this:

    <!-- main content -->
    <div id="leftpanel">
        <h3>This content will be replaced</h3>
        You can <a href="#" onClick="updateFromURL('/MyStrutsApp/AddBook.jsp)">add a book</a>
    </div>
    

    The Javascript code would look like this:

    <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript"></script>
    <script type="text/javascript">
    function display_wait(s) {
      var mainPanel=dojo.byId("leftpanel");
      mainPanel.innerHTML='<div class="waitingmsg">'+s+'</div>';
    }
    
    function updateFromURL(url) {
        display_wait("loading content");
        dojo.xhrGet({url:url,
                    load:function(result) {
                    dojo.byId('leftpanel').innerHTML=result;
                }});
    }
    </script>
    

    (As Rafa mentioned, you can use the same technique to display the new part in a dialog)