2

Possible Duplicate:
How do you execute a dynamically loaded JavaScript block?

I have seen many questions like mine here, but I didn't find an answer which is fitting for me.

I'm loading Code via AJAX, also including a script Tag including Javascript. As I already found out, this Javascript is not executed.

I also found out that eval() can help me, but as I'm a noob in Javascript and just need it for this one time, I have no idea where exactly to put it.

My PHP script is returning a string which I split with Javascript to put it into different parts of the page. This is working fine. One of the parts consists of this:

<div id=\"fb-root\"></div> <script>(function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) return;js = d.createElement(s); js.id = id;js.src = \"//connect.facebook.net/de_DE/all.js#xfbml=1\";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script>

Included like this:

document.getElementById("id").innerHTML=response1;

Where response1 is the variable where I have put the code from above after splitting the string. Anyone able to help me in a noob, easy way?

Community
  • 1
  • 1
Laura
  • 3,233
  • 3
  • 28
  • 45
  • Could you give a little more example code? – Josh Mein Aug 18 '12 at 18:19
  • If you can modify the server, you can make it sends the code in script part separately (e.g. JSON, different field), and execute eval on the received code. Not sure if this is good practice, though (using eval part). – nhahtdh Aug 18 '12 at 18:21
  • how come this answer does not solve your problem? http://stackoverflow.com/questions/75943/how-do-you-execute-a-dynamically-loaded-javascript-block?rq=1 – Shiplu Mokaddim Aug 18 '12 at 18:27
  • it could, but it would be better if it would be the same div. and as i said, im not familiar with javascript so it would be better for me if it would be a thing fitting my code from above. – Laura Aug 18 '12 at 18:32

1 Answers1

9

You can use eval(). You have to give an ID to your script:

<script id='script'>
     some javascript
</script>

And then after loading your ajax response, for loading the script you add this line:

eval(document.getElementById('script').innerHTML);

Good luck!

Guillaume le Floch
  • 1,083
  • 2
  • 11
  • 23