Imagine receiving a response to an AJAX data load request containing a combination of JavaScript and HTML, like this:
<script>window.alert('Hello World!');</script>
<p>This is a paragraph. Lorem ipsum dolor sit amet...</p>
If I simply insert this response into a div
or another container, the script won't be executed automatically. I understand that using the eval()
function can achieve this (as shown in the example below), but eval
is generally discouraged. So, how can I handle this situation properly? Note: I am not utilizing jQuery.
Here's an illustration of an AJAX loader:
function Load(id,url){
var ajax=new XMLHttpRequest();
ajax.onreadystatechange=function(){
if(ajax.readyState!=4)return;
var obj=document.getElementById(id);
if(!obj)return;
obj.innerHTML=ajax.responseText;
// execute any scripts
var scripts=obj.getElementsByTagName('script');
for(var i=0;i<scripts.length;++i)window.eval(scripts[i].innerHTML); // <-- not recommended
}
ajax.open("GET",url,true);
ajax.send(null);
}