Running code from a string

O

ofiras

Hi,
I have a JavaScript code that fetches code lines from another page
into a string, but I don't know how to run this code in the page I
need.
I've tried this but it didn't work:

var code; //my javascript code
document.getElementById('tojs1').innerHTML = 'function fill_mish1()
{'+ code +'}';
fill_mish1();

While in my page there is a line:

<script id='tojs1' type=text/javascript> </script>

Please help,
Ofir.
 
M

Martin Honnen

ofiras said:
I have a JavaScript code that fetches code lines from another page
into a string, but I don't know how to run this code in the page I
need.
I've tried this but it didn't work:

var code; //my javascript code
document.getElementById('tojs1').innerHTML = 'function fill_mish1()
{'+ code +'}';
fill_mish1();

That sounds like a justified use of eval:
eval(code);
 
G

Gordon

Hi,
I have a JavaScript code that fetches code lines from another page
into a string, but I don't know how to run this code in the page I
need.
I've tried this but it didn't work:

var code; //my javascript code
document.getElementById('tojs1').innerHTML = 'function fill_mish1()
{'+ code +'}';
fill_mish1();

While in my page there is a line:

<script id='tojs1' type=text/javascript> </script>

Please help,
Ofir.

You can use eval() to run a string as a piece of JavaScript code. But
please, for the love of fluffy kittens, be extremely careful with
this! The potential for abuse should be obvious, and in addition, eval
()ed code runs more slowly, especially in the newfangled JIT
JavaScript engines that are in vogue at the moment because it can't be
sensibly compiled for future use. You'll also have a hell of a time
debugging a wayward piece of eval()ed code.
 
J

Jorge

Hi,
I have a JavaScript code that fetches code lines from another page
into a string, but I don't know how to run this code in the page I
need.
I've tried this but it didn't work:

var code; //my javascript code
document.getElementById('tojs1').innerHTML = 'function fill_mish1()
{'+ code +'}';
fill_mish1();

While in my page there is a line:

<script id='tojs1' type=text/javascript> </script>

Please help,
Ofir.

Use eval() as Martin pointed out, or (new Function(code))(); The
former will -usually- run 'code' in the current context, the latter
will execute it in the context of an anonymous, top-level function :
i.e. it is equivalent to :

<script>
(function () { code })();
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,161
Latest member
GertrudeMa
Top