Okay, there's three parts to this script; one part which gets the correct request for the client's browser, another which makes the request and another which waits and then handles the output.
To get the correct request we'll check if "window.XMLHttpRequest" returns true, if it does then this function is available and we'll use it; if it returns false then we'll assume the client's browser is Internet Explorer, and therefore create the correct request object for Internet Explorer.
Now we've got the correct request object, we'll create a new GET request to retrieve our JavaScript file. Under the request is an event, which will call a function (which handles the output) once a change is detected.Code:if (window.XMLHttpRequest) { var request = new XMLHttpRequest(); } else { var request = new ActiveXObject('Microsoft.XMLHTTP'); }
The following script checks that the request is on currently on the correct state (where it has retrieved all our script), once the correct state is met we use the "eval()" function to run the response text string.Code:function getJS() { request.open('get','script.js'); request.onreadystatechange = runJS; request.send(null); }
Bellow is a final example of the script, and I've supplied a link to a working example underneath.Code:function runJS() { if(request.readyState == 4) { eval(request.responseText); } }
http://joshjh.pwp.blueyonder.co.uk/AJAXExample.htmCode:<SCRIPT TYPE="TEXT/JAVASCRIPT"> <!-- if (window.XMLHttpRequest) { var request = new XMLHttpRequest(); } else { var request = new ActiveXObject('Microsoft.XMLHTTP'); } function getJS() { request.open('get','script.js'); request.onreadystatechange = runJS; request.send(null); } function runJS() { if(request.readyState == 4) { eval(request.responseText); } } document.write('Get & run JS'.link('javascript:getJS();')); --> </SCRIPT>





Reply With Quote







