0

I have a page with headers, images, etc. I'd like to replace a "page" div with another file of HTML, JavaScript, etc using Ajax and execute JavaScript on that page after it is loaded. How do I do this and also handle < , ", and other tags in the file and pass the page some parameters?

Luca Putzu
  • 1,438
  • 18
  • 24
John Wooten
  • 685
  • 1
  • 6
  • 21

3 Answers3

0

Is the other "page" content owned by you? If so, you can have javascript methods on your main "container" page, then once you fire the method to pull the contents of the new "page" div, fire the corresponding javascript method you need, since any necessary DOM elements will have been added to the page at this time.

To do it the way you mentioned, you can follow the steps seen here to use the dynamic script pattern: Executing <script> inside <div> retrieved by AJAX

Basically, you host your javascript externally, then once the page has loaded, add the "src" tag to a script element and it will execute.

As for handling special characters, you can follow steps with jQuery's ajax call to inject HTML from the other page into your current one, such as here: How to get the html of a div on another page with jQuery ajax?

$.ajax({
url:'http://www.example.com/',
    type:'GET',
    success: function(data){
       $('#ajaxcontent').html($(data).find('body').html());
    }
});

(Instead of targeting a specific div on the external page, you would target the body or parent container div)

Community
  • 1
  • 1
AdmanStrong
  • 323
  • 1
  • 8
0

given an html page

<html>
...
<body>
   <div class="page">
      some html content...
   </div>
</body>
</html>

you can replace the content of the div via the jQuery function load()

$("div.page").load("an-http-resource.html");
Luca Putzu
  • 1,438
  • 18
  • 24
0

Use an AJAX request to get the HTML file as a response. Replace the "page" div innerHTML with the response. If the HTML page has a bunch of headers and such and you only want a certain portion of that HTML file, you may want to use getElementById or some other method of selecting the portion of the HTML file.

The HTML entities will appear as they normally would in a browser, if that is what you mean by handling < and " and other tags.

You can send parameters by editing the endpoint:

index.html?date=today&car=yours
Robert Broden
  • 118
  • 4
  • 11
  • Thanks. Got this to work using the load function. If the page is not named html, but contains a mixture of javascript and html, can parameters still be attached and how do you get to them? – John Wooten Feb 19 '16 at 00:47
  • usually the parameters are received by the server. However, if you want to use javascript to get the paramters. I showed some examples of how to do so here: [jsfiddle example](https://jsfiddle.net/robbroden/a2khna6g/) – Robert Broden Feb 19 '16 at 02:30