A Jquery way to include file

1 1 1 1 1 1 1 1 1 1 Rating 4.33 (3 Votes)

{flike}

Although all server side components provide the option of including file like <jsp:include> etc, having a way to include files using clients side script can come handy if the pages are made of plain old HTML.

We provide a code for explaining how Jquery can be used to include files.

Main file:


<html>
 <head>
  <script type="text/javascript" src="/static/jquery-1.3.1.js"></script>
  <script type="text/javascript">
   //Gets called after the page is completely loaded
   $(document).ready( function() {
    //loads include page using AJAX passing parameters and executes the function after completion
    $("#include").load("incJquery.jsp", {param1:25, param2:30}, function() {
     alert("Loading include file completed!");
    });
   });
  </script>
 </head>
 <body>
  <div id="include">Loading....</div>
  Welcome to Jquery <br/>
  You see me in the main file!
 </body>
</html>
{/codecitation}

Include file:

{codecitation class="brush: html;"}
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<h2>Am from include file, thanks to Jquery!</h2>
Value of Parameter1 is <c:out value="${param.param1}"/>
<br/>Value of Parameter1 is <c:out value="${param.param2}"/><p/>


The jquery load function basically is an AJAX call which loads the content and inserts it into the div with id=include.

The load used uses the three parameter function. The first parameter being the URL, second is data (which is basically a key/value pair object) and lastly a function. The data (key/value) gets passed to the URL as parameters. The include file can access the parameters like any GET parameters received.

Add both the files in a Java application server context. The files should be placed in same directory. Access the main file from browsers using a localhost url for going through the application server.

See the contents loaded from include file and also the parameter contents received in the include file.

 

  • Do not try to load pages from a different domain using the above script. It will not work and will provide a cross domain access error.

 


Joomla SEO by MijoSEF