人气:349 发布:2022-09-11 标签: http cross-domain scripting javascript ajax



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("Error loading page");


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?


你是对跨越域发出请求,除非你正在使用跨域资源共享(CORS,的 http://www.w3.org/TR/cors/ )。 CORS具有客户端和服务器端组件。在客户端,请求看起来多为像一个普通的XmlHtt prequest,除非你有一些其他的特性和处理程序,您可以配置。在服务器上,响应将需要发出一些特殊的HTTP标头。本文给出了CORS是如何工作的客户端和服务器上的一个很好的细分:http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

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/