在Ajax XMLHttpRequest中包含js文件

时间:2012-03-15 17:46:21

标签: php ajax xmlhttprequest

我正在使用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文件。 有可能吗?

1 个答案:

答案 0 :(得分: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!!");
相关问题