Sunday 15 August 2010

javascript - eval JS in AJAX loaded contents -


I want to load this code (1) in another page via XMLHttpRequest

  & lt; Input type = "text" onkeypress = "info (event)" /> & Lt; Script & gt; Function information (e) {console.log (e.keyCode); } & Lt; / Script & gt;   

This is (2) the way I tried ...

    

... and this is the error I got on the keypress:

  Unfair reference references: Information is not defined   

Why info () has not got its definition since eval'd? How (2) should be unaware of how to press information (1)? No jQuery

After the recommendation of Mike, I have created a solution to solve the problem which explains the problem.

area you did not leave it on the window In the handleResponse it will not be present outside the handleResponse. In addition, in this case you do not really need to eval just do this:

  function handle response () {var x = document.getElementById ("x"); X.innerHTML = this.responseText; // Hold all the script elements, as an array // (instead of document .query s .. 's node list reply) var js = [] .slice.call (x.querySelectorAll ("script"), 0 ); // Add all those scripts to the head element. Js.for every (Task (Script Element) {document.head.appendChild (scriptElement); // This script element runs from [x] to [head]}; < / Code>  

The browser already knows to interpret the script, but you need to add elements in the head if you execute them instead of putting them in the form of disabled DOM Nodes.

Finally, if you actually get the eval (which is above If the requirement is not 99.99%), then new function is very good because it will allow you to catch both syntax and runtime errors instead of "Who knows":

  try {var evaluator = new function ("return" + Js.innerText + ";"); {attempter (try);} hold (runtime error) {console.log ("error : Eval'd code is legal, but runtime broken ");}} Catch (syntax error) {console.log (" Error: syntax errors in js.innerText May include ");}    

No comments:

Post a Comment