Jeff Escalante
Jeff Escalante

Reputation: 3167

Loading Scripts with AJAX

I have set up a page so that it loads content in with AJAX by selector. This is how the code looks, for anyone who isn't familiar

$('#container').load(content.php + .classname)

Super straightforward. Each div I load, I also have a little block of script in the bottom, holding variables for the identification of that block, which I am keeping track of separately. For example:

<div class="classname"> 
    <p>Here's my content!</p> 
    <script> var contentID = 4; </script> 
</div>

The problem I have run into is that when I load in the content, while all the content comes in totally fine, it's not loading in the script, it just cuts that entire section right out.

Anyone have any idea why this is happening, or how to solve this problem? I am aware of the getScript() function, but I need to load in both html and script at the same time. In addition, i have a bunch of different things to load, with just about one line of unique script for each one, so it would be a total waste to make an external JS file for each one...

Upvotes: 1

Views: 250

Answers (1)

Richard Schneider
Richard Schneider

Reputation: 35477

You will need to find the <script> and eval it. See http://www.w3schools.com/jsref/jsref_eval.asp

If you are using jQuery,then you can do:

$('#container script').each(function (i) {eval(this.innerHtml()} ));

Upvotes: 1

Related Questions