在由xmlhttprequest加载的页面中运行javascript

时间:2011-07-11 09:54:57

标签: php javascript html css xmlhttprequest

在我的javascript方法中,我调用xmlhttprequest来获取一些数据并将其显示在名为“myDiv”的div中(index.php)

function combo_change(theid)
{
  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)
    {
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","anotherpage.php?id=" + theid,true);
  xmlhttp.send();
}

现在,我正试图在页面“anotherpage.php”中调用一些javascript,但它不想工作。作为测试,我只是做document.write('hello');。如果我直接加载页面它会显示,但是当通过xmlhttp打开时使用代码时它不会。

我可以假设在这样加载时,javascript没有运行。那么,无论如何我能让它运行吗?

2 个答案:

答案 0 :(得分:1)

将您的JavaScript代码写在

if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
  document.getElementById(\"myDiv\").innerHTML=xmlhttp.responseText;
  //Your js code 
}

答案 1 :(得分:1)

看看这个:http://zeta-puppis.com/2007/05/27/javascript-script-execution-in-innerhtml-another-round/

简短版本:document.write()有问题,请尝试alert()查看您的脚本是否运行。