I am running a node.js back-end with a Web based javascript client to send AJAX requests.
Now, I would like to do a small desktop version of the javascript client using pure Javascript, i.e. Google's V8.
In this scenario, how could I enable the AJAX support for the desktop version as there are no window / document objects ? In a perfect world in such a way that the Web and Desktop versions would share the same code ?
Or would I need to write the AJAX or REST API outside the js code, i.e. as native code and call it from js ?
As Brad, says, there is currently no way to make an http request from the ECMAScript non-web implementations, even though there is a working draft at http://www.w3.org/TR/XMLHttpRequest/ to integrate XMLHttpRequest to these implementations as well (I guess through external bindings).
What I did was to create a global function and implement it in the Web version like this:
function SendBackendRequest( url, parameters, func )
{
var request=new ajaxRequest();
request.onreadystatechange=function() {
if (request.readyState == 4) {
if ( request.status == 200 || window.location.href.indexOf("http") ==-1 ) {
func.call( this, request.responseText );
} else {
func.call( this, "" );
}
}
}
request.open( "POST", "http://localhost" + url, true );
request.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
request.send( parameters );
};
ajaxRequest=function()
{
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
if ( window.ActiveXObject ) {
// --- IE
for (var i=0; i<activexmodes.length; i++) {
try {
return new ActiveXObject(activexmodes[i])
}
catch(e) {
//suppress error
}
}
} else
{
if (window.XMLHttpRequest) // --- Mozilla, Safari etc
return new XMLHttpRequest();
else return false;
}
};
On the Desktop side I just implemented SendBackendRequest() as well and inside my client code can use the same code to communicate with the backend.