tags:

views:

35

answers:

3

Hi, I am trying to call one jsp files from Jquery-ajax call. But, I can able to get only pure html. It is not loading any css files and js files while loading html. so html page is coming with out style sheets.

here, sample code updated

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Welcome</title>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 </head>
 <script type="text/javascript" src="js/Global/jquery-1.4.2.js"></script>
 <script type="text/javascript">
  function ajaxJq()
  {
   $.get('test.jsp', function(data) 
         {
            $('#myDiv').html(data);
            alert('Load was performed.');
         });
  }
 </script>
 <body>
  <div id="myDiv"></div>
  <div id="error"></div>
  <button id ="buttonAjax" type="button" onclick="ajaxJq()">Ajax Call</button>
 </body>
</html>

test.jsp contains js files and css files. If i see that, test.jsp loading f

+3  A: 

When you load content with AJAX, the returned content should be only an HTML fragment.

If you load a complete HTML document and put it into the page, the resulting HTML code is invalid, as a document can not be inside another document. Different browsers behave a little different on invalid code, but no browser will ever load the css files and apply them only to the loaded content.

If you want to load a complete HTML document, then you should use an iframe instead of loading the content using AJAX.

Guffa
A: 

You would need to do the work manually.

function ajaxJq() {
    $.get('test.jsp', function(data) {
         var $html = $(data);

         $html.find('script').each(function(i,e){
             $('head').append(e);
         });
         $html.find('link').each(function(i,e){
             $('head').append(e);
         });

         $('#myDiv').html($html.find('body').contents());

         alert('Load was performed.');
    });
}

But in general, this is maybe not a good way to do it. Using an iframe is maybe a lot more efficient here since you cannot load another <html> or <head> tag into another page / DOM.

jAndy
+1  A: 

That's expected behaviour. When you try to load an entire HTML page into an existing page element such as a DIV, most browsers will strip out scripts, stylesheets and any other meta-content such as the title. Possible workarounds for styling are:

  • include the additional CSS files in your main page
  • use inline styles in the retrieved page
casablanca