1

I'm using Ajax and code which is described below. I want to include .js file in Ajax XMLHttpRequest. Does anybody know how to do that?

For example: I have code below:

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;
}

When program call function MakeRequest(id) then i want to also executed some .js file. Is it possible to do that?

1
  • By "I want to include .js file in Ajax XMLHttpRequest." do you mean "I want to add JS to the page using innerHTML and have it execute"? The XMLHttpRequest seems to be something of a red herring. Commented Mar 15, 2012 at 17:48

1 Answer 1

1

You could always put this code in your function to cause a script to be loaded and executed...

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

Here's a complete example. These two files just need to be in the same folder on the server.

This is 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>

And this is hello.js:

alert("helloooo!!");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answer, but this not help.
yeah, tested it in a more complete example just to make sure I hadn't dropped any bits on the floor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.