尝试不使用eval()
:
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=xmlhttp.responseText;
}
}
xmlhttp.open('GET','file2.php',true);
//xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //unnecessary for GET calls
xmlhttp.send(null);
Eval
使用您的代码<script...></script>
是不必要的,javascript 代码将在添加到 DOM 后立即执行。
新编辑:
您必须消除\n\r
reponseText 中的换行符才能eval
正确使用您的脚本。\
此外,在第一个转义字符之前还有一个额外的转义字符,<
它破坏了您的代码。尝试:
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(/\n|\r/g, " ").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(null);
I've added a .replace(/\n|\r/g, " ")
to replace all line breaks by an white space in your responseText
, 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
:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Your AJAX call would be as simple as:
<script type="text/javascript">
$(document).ready(function(){
$('#div').load('file2.php');
});
</script>
JQuery automatically parses scripts from your responseText, as noted in your linked answer.