Execute javascript function on page sent using AJAX response

I want to execute a function that is sent at the AJAX request from the server. The body of the function is not on the calling page. For example: (full code is below)

1.calling php script:

<script> function fun() { try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ document.getElementById("rslt").innerHTML = ajaxRequest.responseText; } } ajaxRequest.open("GET", "ajax_js2.php", true); ajaxRequest.send(null); } </script> <input type="button" onclick="fun()"> <div id="rslt"> </div> 

2.ajax_js2.PHP script:

 <script> function test() { alert("Hello"); } </script> <span onclick="test()">Test AJAX</span> 

I know that the definition of the "test" function will be executed in the calling script. But I want to save it in a second script. What should I do? The server returns the range as a response to the client. Pressing the space bar "AJAX Test" should call the function.

+4
source share
1 answer

<script> tags inserted in the DOM will not execute unless you run eval() . More details here: Is it possible to insert scripts using innerHTML?

So, in your case, test() will be undefined when you try to click on a range because the script code was not executed (thus, it never defined the test function).

You can get around this using something like this (after the DOM injection):

 var scripts = document.getElementById("rslt").getElementsByTagName("script"); for( var i=0; i<scripts.length; i++ ) { eval(scripts[i].innerText); } 

(ps eval not evil)

+7
source

Source: https://habr.com/ru/post/1500909/


All Articles