views:

44

answers:

2

Bit of a JavaScript newbie here -

I am firing this basic bit of JavaScript code from my website as a test:

var req = new XMLHttpRequest();
req.open('GET', 'http://www.google.co.uk/', false);
req.send();
if (req.status == 200) {
    alert(req.responseText);
}

and I keep getting the following error:

[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.send]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost/testEx3/Default.aspx :: SendRequest :: line 402" data: no]

Does anyone know what I'm doing wrong here?

UPDATE:

OK - so what I'm actaully trying to do is a POST request to a web service I published on my local dev machine - I was getting the same error as above - that's why I put that example for simplicity. It now appears the "Same Origin Policy" has come into play - so now I have published the web service with the begining part of the URI as http://localhost/ instead of http://tempuri.org/.

Now I get a 500 error. Is there something I am missing in the headers?

var request = new XMLHttpRequest();
request.open("POST", "http://localhost/ApplicationServices.asmx?op=AddressSearch", false, "", "");
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");

request.send(x, y, buffer);

if (request.status == 200) {
    alert("Success");
}
else {
    alert("Failure: " + request.status);
}
+1  A: 
Pointy
OK - well actually I'm really try to do a POST request to a Web Service Im hosting locally - and it still gives the same error. I just thought I would put the google url just to make my question easier to understand - I had no idea about this "same orign policy". Surely it can't be that hard to access your own web sercvice.
Vidar
OK see my edit.
Pointy
+4  A: 

It looks like you're trying to send a request that would violate the same origin policy.

Basically, in terms of AJAX requests, you're limited to sending requests to the same domain as the page sending that request. For example:

You're trying to do #3 above.

If you need to send a cross-domain request, you can using JSONP or something like flensend/flxhr.

ajm
I have a sneeky feeling this is massive overkill for me - as all I trying to do is a simple POST request to a webservice I have published on my local machine. Is there an easier way?BTW - I still get the same error with the POST request.
Vidar