views:

414

answers:

3

i have the following javascript in my webpage:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.google.com', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    alert('resp received, status:' + xhr.status + ', responseText: ' + xhr.responseText);
  }                                                                       
};                                                                        
xhr.send(null);

this executes and finishes w/ a readyState of 4, status of 0, and empty responseText and responseXML. i know that it is actually sending the request b/c i tried sending the xhr to a server on my machine, and the server does in fact respond. why am i not getting anything in the responseText? does it have something to do w/ the fact that the xhr is going to a different server?

when i open up the js debugger and type 'xhr' to inspect the object i get this:

XMLHttpRequest
DONE: 4
HEADERS_RECEIVED: 2
LOADING: 3
OPENED: 1
UNSENT: 0
abort: function abort() {
addEventListener: function addEventListener() {
dispatchEvent: function dispatchEvent() {
getAllResponseHeaders: function getAllResponseHeaders() {
getResponseHeader: function getResponseHeader() {
onabort: null
onerror: null
onload: null
onloadstart: null
onprogress: null
onreadystatechange: function () {
open: function open() {
overrideMimeType: function overrideMimeType() {
readyState: 4
removeEventListener: function removeEventListener() {
responseText: ""
responseXML: null
send: function send() {
setRequestHeader: function setRequestHeader() {
status: 0
statusText: ""
upload: XMLHttpRequestUpload
withCredentials: false

+1  A: 

You can't do cross-domain requests with javascript. The best way round this is to use your server as a proxy.

Ben Shelock
+9  A: 

does it have something to do w/ the fact that the xhr is going to a different server?

Yep, you cannot send requests to another servers via AJAX. Whereas, you can send your requests from the server-side. Thus you'll need to implement following workflow: Your page -> Your server -> Third party server -> Your server -> Your page , where "->" means sending data.

Li0liQ
+1 an effective very simple proxy. I have written one of these in PHP using CURL.
tgandrews
+2  A: 

Cross-site scripting is a common way of injecting code into someone else's web page. To limit this, most browsers now stop the client-side developer from creating a JavaScript request (typically through XMLHttpRequest) to web pages located on a different domain to the original page.

You can get around this simply by creating a dummy script on your domain that forwards the same request to the page you actually want. For example, in your case, you would create a request to http://mydomain.com/google.php (or whatever scripting language you prefer), which would then download the Google page using file_get_contents or similar and simply echo it out.

Samir Talwar