Tom
Tom

Reputation: 3627

Replace Javascript code and run it

Suppose I have this code:

my_script_data = document.getElementById("id_php_defer__core");
if (my_script_data == undefined) {
  Alert(request.responseText); // all looks good!
  my_script_data = document.createElement("script");
  my_script_data.setAttribute("id", "id_php_defer__core");
  my_script_data.innerHTML = 'function myinitfunc() { ' + "\n" + request.responseText + "\n" + ' }';
  to = document.head;
  if (to != undefined) {
    to.appendChild(my_script_data);
  }
}
else {
  Alert(request.responseText); // all looks good!
  my_script_data.innerHTML = 'function myinitfunc() { ' + "\n" + request.responseText + "\n" + ' }';
  eval(my_script_data.innerHTML);
}

The "request.responseText" is actually a Javascript array declaration with lots of values set.

After above code, the "myinitfunc" is called later.

(And as it should only contain "request.responseText" the global (!) array of values should be updated.)

However, while the code works on first run, subsequent runs seem to do nothing, so I am doing something wrong, but what? :)

Upvotes: 0

Views: 151

Answers (2)

Rob W
Rob W

Reputation: 348992

<script> tags cannot be recycled. To fix that, you decided to use eval.

However (certainly in strict mode), eval does not run in the current nor global scope. As a result, the declared function does not show up.

I strongly discourage using eval for this purpose. You said that responseText contains an array. By tweaking a bit, you can use JSON to handle data.

You can also insert and remove a script element in the following way:

var s = document.createElement('script');
s.appendChild(document.createTextNode(request.responseText));
// ^ Equivalent to a "global eval"
(document.head || document.getElementsByTagName('head')[0]).appendChild(s);
s.parentNode.removeChild(s);

Upvotes: 1

Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9696

Did you try to eval() every time you call myinitfunc()?

Upvotes: 0

Related Questions