AJAX和跨站点脚本读取页眉

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

问题描述

帮助我了解AJAX和跨站点脚本更好一点。编写Ajax是相当简单的。如果我想要异步读取网页的HTTP头,我会做这样的事情:

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);

然而,当我复制和使用记事本粘贴到一个简单的HTML页面,并尝试在本地运行,请求状态似乎并没有返回200我假定这是由于跨站点脚本。我该如何解决这个?

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/

108