【问题标题】:Include js file in Ajax XMLHttpRequest在 Ajax XMLHttpRequest 中包含 js 文件
【发布时间】:2012-03-15 17:46:21
【问题描述】:

我正在使用 Ajax 和下面描述的代码。我想在 Ajax XMLHttpRequest 中包含 .js 文件。有人知道怎么做吗?

例如: 我有以下代码:

function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
  return xmlHttp;
}

function MakeRequest(id)
{
  var xmlHttp = getXMLHttp();

  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      HandleResponse(xmlHttp.responseText);
    }
  }

  xmlHttp.open("GET", "updatesite.admin.php?id="+id, true);
  xmlHttp.send(null);
}

function HandleResponse(response)
{
    document.getElementById('Vsebina').innerHTML = response;
}

当程序调用函数 MakeRequest(id) 时,我还想执行一些 .js 文件。 有可能吗?

【问题讨论】:

  • 通过“我想在 Ajax XMLHttpRequest 中包含 .js 文件。”您的意思是“我想使用innerHTML 将JS 添加到页面并让它执行”? XMLHttpRequest 似乎是一个红鲱鱼。

标签: php ajax xmlhttprequest


【解决方案1】:

您总是可以将此代码放入您的函数中,以使脚本被加载和执行...

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://location-of-script.js";
document.body.appendChild(script);

这是一个完整的例子。这两个文件只需要在服务器上的同一个文件夹中。

这是 hello.html:

<html>
<head>
<script type="text/javascript">
function doit()
{
  var scr = document.createElement('script');
  scr.type = "text/javascript";
  scr.src = "hello.js";
  document.body.appendChild(scr);
}
</script>
</head>
<body>
<input type="button" value="hello" onclick="doit();">
</body>
</html>

这是 hello.js:

alert("helloooo!!");

【讨论】:

  • 感谢您的回答,但这无济于事。
  • 是的,在一个更完整的示例中对其进行了测试,以确保我没有在地板上掉下任何碎片。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 2017-12-22
  • 1970-01-01
  • 2012-07-14
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多