Whats wrong with this code or what might be causing this problem? It’s not alerting “hello”, but it is filling the div with The Hello and Bye World tables. I want it to alert “hello”. Also I don’t know jquery. Thank You
FILE1
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = xmlhttp.responseText.replace(reScript, function(m,m1) {
eval(m1);
return "";
});
document.getElementById("div").innerHTML=response;
}
}
xmlhttp.open('GET','file2.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send();
FILE2
<table><tr><td>Hello World</td></tr></table>
<script type="text/javascript">
alert('hello');
</script>
<table><tr><td>Bye World</td></tr></table>
Try without theeval():Evaluing your code inside the<script...></script>is unnecessary, the javascript code will be executed as soon as it’s added to the DOM.New edit:
You have to eliminate the linebreaks
\n\rin your reponseText in order for your script to beevaluated properly. Also, there was an extra\escape character before the first<which was breaking your code. Try:I’ve added a
.replace(/\n|\r/g, " ")to replace all line breaks by an white space in yourresponseText, which will allow for your JS to be evaluated properly and cause no visible change to the end-user. You may also replace the white space" "by an empty string""if all of your JS is properly semi-colon’d.The above should work fine for simple scripts, now if you’d include the JQuery lib in your page’s
head:Your AJAX call would be as simple as:
JQuery automatically parses scripts from your responseText, as noted in your linked answer.