【问题标题】:Running javascript in a page loaded by xmlhttprequest在 xmlhttprequest 加载的页面中运行 javascript
【发布时间】:2011-10-02 16:04:48
【问题描述】:

在我的 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 没有运行。那么,无论如何我可以让它运行吗?

【问题讨论】:

  • 为了快速而肮脏的 hack,您可以使用 eval。不过我不推荐它。
  • 为什么你的引号被转义了? (不要说“因为它在 PHP 脚本中”——这不是一个可以接受的理由)
  • 好地方。这样做有什么问题?

标签: php javascript html css xmlhttprequest


【解决方案1】:

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

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

【讨论】:

  • +1 这看起来很有趣,但现在有点重写。稍后将不得不执行此操作!谢谢。
【解决方案2】:

在里面写你的 JavaScript 代码

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

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 2017-05-21
    • 2016-08-18
    • 1970-01-01
    • 2013-03-19
    • 2017-01-20
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多