I'm trying to cobble together a php style include function for javascript. The route I'm taking is through a XMLHttpRequest. The included file will load, but the functions in that file aren't available as their scope is limited to the function that is calling them.
I came across this article which achieves a similar goal, but requires the coder to specify which functions they require in advance, while I would like to simply include a file and automatically add the functions the window object.
Here's my progress
function twinkle(){
getXMLHTTPObj("twinkle/test.js");
// A simple function inside test.js
includedFunc();
}
// XMLHttp Stuff lifted from he Apple tutorial
var req;
function getXMLHTTPObj(url) {
req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
// Set to False so javascript waits for the included functions
// to become available
req.open("GET", url, false);
req.send("");
}
return req;
}
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
eval(req.responseText);
} else {
alert("There was a problem retrieving the XML data:\n" +
req.statusText);
}
}
}
I'm considering creating an index of functions inside each included file that can be iterated over when the file is included, but that's not really an elegant solution.
Any ideas? Is there some javascript property or function I can access to get a list of functions in the file?