日期:2014-05-16  浏览次数:20725 次

求xmlHttp.responseText返回<script>的最好方法 - Web 开发 / Ajax
//使用的函数如下
function   ajax(){
try{
var   url   =   "test.asp ";
xmlHttp.open( "GET ",   url,   true);
xmlHttp.onreadystatechange   =   ajaxOk;
xmlHttp.send(null);
}catch(exception){}
}

function   ajaxOk(){
if   (xmlHttp.readyState   ==   4)   {
try{
var   response   =   xmlHttp.responseText;
var   alertObj   =   document.getElementById( "ajaxalert ");
alertObj.innerHTML=response;
}catch(exception){}
}
}

//如果test.asp中response.write的是html则显示正常,请问有什么方法能即返回html又返回html中的 <script> ,比如test.asp中返回 <script> alert( '123 ') </script> 。?

//在网上找了好多资料,只知道用eval(),但不知在我的这个函数里应该怎么用,或者有没有更好的办法,请指教。

------解决方案--------------------
//得到返回的字符串
var response=xmlHttp.responseText;
//匹配一个 <script> </script> 标签,找出js代码
response=response.replace(/ <script> (.*) <\/script> /gi, "$1 ");
alert(response);
//执行
eval(response);
------解决方案--------------------
楼上正解.
建议将js集中代码放入一个.js文件,由ajax读出后再eval一下就OK了,dojo框架的动态载入模块就是这样弄的.