在xmlhttprequest加载的页面中运行javascript

Running javascript in a page loaded by xmlhttprequest

本文关键字:运行 javascript xmlhttprequest 加载      更新时间:2023-09-26

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

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没有运行。有什么办法能让它运行吗?

内编写JavaScript代码
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
  document.getElementById('"myDiv'").innerHTML=xmlhttp.responseText;
  //Your js code 
}

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

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