2

Help me understand AJAX and cross-site scripting a little better. Writing AJAX is fairly straight forward. If I want to asynchronously read HTTP header of a website, I'd do something like this:

var req = new XMLHttpRequest();
req.open('HEAD', 'http://www.stackoverflow.com/', true);
req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
     if(req.status == 200)
      alert(req.responseText);
     else
      alert("Error loading page");
  }
};
req.send(null);

However, when I copy and paste this into a simple HTML page using notepad and try to run it locally, the request status doesn't seem to return 200. I am assuming this is due to cross-site scripting. How would I get around this?

4 Answers 4

2

You are right in that making requests across domains is not allowed unless you are using Cross-Origin Resource Sharing (CORS, http://www.w3.org/TR/cors/). CORS has a client-side and server side component. On the client side, the request looks mostly like a regular XmlHttpRequest, except you have a few other properties and handlers you can configure. On the server, the response will need to emit some special http headers. This article gives a good breakdown of how CORS works on the client and server: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

1

My first guess would be to try and make a local PHP file which acts like a gateway:

<?php
  echo get_headers($_GET['url']);
?>

Then, perform a GET request with the url of your target site as the parameter, and parse the .responseText of that request to determine the response header of your original.

I don't think it's possible with pure JS, so you'll have to use some serverside code.

0

There are two types of "locally":

  • Using a local server (http://localhost/)
  • Accessing HTML file directly (file:///C:\a\b\c.html)

AJAX won't work, ever, in the second case.

0
0

You can't make an ajax request to http://stackoverflow.com if your page is being served on http://localhost/...

http://en.wikipedia.org/wiki/XMLHttpRequest#Cross-domain_requests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.