First of all: It’s not possible to get directly content from other servers outside the domain with XMLHttpRequest. But if there is no direct way, it must have an undirect way
. Well the solution is simply but genius. You call a local proxy, telling it to load the content from the other server and pass the request results to the XMLHttpRequest. That works fine.
In my case I tried to load data from another server for analyzing its link sturcture. I wrote a proxylike script that takes an URL, creates a request to the destination server and sends back the servers response. I’ve written the proxylike script in PHP. Here it is:
/* Create a client that connectes to the given URL and gets the content */
require_once( ‘http.inc’ );
$http_client = &new http( HTTP_V11, false);
$http_client->user_agent = “”;
/*Set the host and get content*/
$http_client->host = $_GET[’host’];
$code = $http_client->get($_GET[’contentpath’]);
if ($code != HTTP_STATUS_OK)
return false;
/*Return the response back to the caller*/
$response = $http_client->get_response_body();
print($response);
?>
You can download http.inc (Advanced HTTP Client) at PHP Classes for free.
Now, you only have to redirect the URL of the content to this proxylike script. Here’s an example how to use the upper proxylike script:
/*Direct URL: http://www.otherserver.com/pathtocontent/content.html*/
var redirectedURL = “http://www.yourserver.com/pathToTheProxyScript/proxy.php”;
redirectedURL += “?host=www.otherserver.com”;
redirectedURL += “&path=/pathtocontent/content.html”;
var request = new XMLHttpRequest();
request.open(”GET”, redirectedURL true);
request.onreadystatechange = function() {
if (request.readyState == 4)
{
_handler.apply( _caller, args );
}
</script>