zoukankan      html  css  js  c++  java
  • AJAX(XMLHttpRequest)进行跨域请求方法详解(二)

    注意:以下代码请在Firefox 3.5、Chrome 3.0、Safari 4之后的版本中进行测试。IE8的实现方法与其他浏览不同。

    2,预检请求

    预检请求首先需要向另外一个域名的资源发送一个 HTTP OPTIONS 请求头,其目的就是为了判断实际发送的请求是否是安全的。下面的2种情况需要进行预检:
    a,不是上面的简单请求,比如使用Content-Type 为 application/xml 或 text/xml 的 POST 请求
    b,在请求中设置自定义头,比如 X-JSON、X-MENGXIANHUI 等

    注意:在 iis 里进行测试,必须在“应用程序扩展”里面配置 .aspx 扩展的动作允许 OPTIONS。

    下面我们举一个预检的请求:

    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    3. <htmlxmlns="http://www.w3.org/1999/xhtml">
    4. <head>
    5. <title>孟宪会之AJAX跨域请求测试</title>
    6. </head>
    7. <body>
    8. <inputtype='button'value='开始测试'onclick='crossDomainRequest()'/>
    9. <divid="content"></div>
    10. <mce:scripttype="text/javascript"><!--
    11. var xhr =new XMLHttpRequest();
    12. var url ='http://dotnet.aspx.cc/PreflightedRequests.aspx';
    13. function crossDomainRequest() {
    14. document.getElementById("content").innerHTML ="开始进行请求……";
    15. if (xhr) {
    16. var xml ="<root>测试</root>";
    17. xhr.open('POST', url, true);
    18. xhr.setRequestHeader("POWERED-BY-MENGXIANHUI", "Approve");
    19. xhr.setRequestHeader("Content-Type", "application/xml");
    20. xhr.onreadystatechange =handler;
    21. xhr.send(xml);
    22. } else {
    23. document.getElementById("content").innerHTML ="不能创建 XMLHttpRequest。";
    24. }
    25. }
    26. function handler(evtXHR) {
    27. if (xhr.readyState == 4) {
    28. if (xhr.status == 200) {
    29. var response =xhr.responseText;
    30. document.getElementById("content").innerHTML ="结果:" + response;
    31. } else {
    32. document.getElementById("content").innerHTML ="不能进行跨越访问。";
    33. }
    34. }
    35. else {
    36. document.getElementById("content").innerHTML += "<br/>执行状态 readyState:" + xhr.readyState;
    37. }
    38. }
    39. // --></mce:script>
    40. </body>
    41. </html>
    [xhtml] view plain copy
     
     print?
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
    2.   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    3. <html xmlns="http://www.w3.org/1999/xhtml">  
    4. <head>  
    5. <title>孟宪会之AJAX跨域请求测试</title>  
    6. </head>  
    7. <body>  
    8.   <input type='button' value='开始测试' onclick='crossDomainRequest()' />  
    9.   <div id="content"></div>  
    10.   <mce:script type="text/javascript"><!--  
    11.   var xhr = new XMLHttpRequest();  
    12.   var url = 'http://dotnet.aspx.cc/PreflightedRequests.aspx';  
    13.   function crossDomainRequest() {  
    14.     document.getElementById("content").innerHTML = "开始进行请求……";  
    15.     if (xhr) {  
    16.       var xml = "<root>测试</root>";  
    17.       xhr.open('POST', url, true);  
    18.       xhr.setRequestHeader("POWERED-BY-MENGXIANHUI", "Approve");  
    19.       xhr.setRequestHeader("Content-Type", "application/xml");  
    20.       xhr.onreadystatechange = handler;  
    21.       xhr.send(xml);  
    22.     } else {  
    23.     document.getElementById("content").innerHTML = "不能创建 XMLHttpRequest。";  
    24.     }  
    25.   }  
    26.   function handler(evtXHR) {  
    27.     if (xhr.readyState == 4) {  
    28.       if (xhr.status == 200) {  
    29.         var response = xhr.responseText;  
    30.         document.getElementById("content").innerHTML = "结果:" + response;  
    31.       } else {  
    32.         document.getElementById("content").innerHTML = "不能进行跨越访问。";  
    33.       }  
    34.     }  
    35.     else {  
    36.       document.getElementById("content").innerHTML += "<br/>执行状态 readyState:" + xhr.readyState;  
    37.     }  
    38.   }  
    39. // --></mce:script>  
    40. </body>  
    41. </html>  

    上面的例子我们发送 xml 格式的数据,并且,发送一个非标准的HTTP头 POWERED-BY-MENGXIANHUI 来说明服务器端该如何设置响应头的。

    在服务器端,PreflightedRequests.aspx 的内容如下:

    1. <%@ PageLanguage="C#" %>
    2. <mce:scriptrunat="server"><!--
    3. protected void Page_Load(object sender, EventArgs e)
    4. {
    5. if (Request.HttpMethod.Equals("GET"))
    6. {
    7. Response.Write("这个页面是用来测试跨域 POST 请求的,直接浏览意义不大。");
    8. }
    9. else if (Request.HttpMethod.Equals("OPTIONS"))
    10. {
    11. //通知客户端允许预检请求。并设置缓存时间
    12. Response.ClearContent();
    13. Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
    14. Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    15. Response.AddHeader("Access-Control-Allow-Headers", "POWERED-BY-MENGXIANHUI");
    16. Response.AddHeader("Access-Control-Max-Age", "30");
    17. //此过程无需返回数据
    18. Response.End();
    19. }
    20. else if (Request.HttpMethod.Equals("POST"))
    21. {
    22. if (Request.Headers["Origin"].Equals("http://www.meng_xian_hui.com:801"))
    23. {
    24. System.Xml.XmlDocument doc =new System.Xml.XmlDocument();
    25. doc.Load(Request.InputStream);
    26. Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
    27. Response.Write("您提交的数据是:<br/><br/>" + Server.HtmlEncode(doc.OuterXml));
    28. }
    29. else
    30. {
    31. Response.Write("不允许你的网站请求。");
    32. }
    33. }
    34. }
    35. // --></mce:script>
    [xhtml] view plain copy
     
     print?
    1. <%@ Page Language="C#" %>  
    2. <mce:script runat="server"><!--  
    3.   protected void Page_Load(object sender, EventArgs e)  
    4.   {  
    5.     if (Request.HttpMethod.Equals("GET"))  
    6.     {        
    7.       Response.Write("这个页面是用来测试跨域 POST 请求的,直接浏览意义不大。");  
    8.     }  
    9.     else if (Request.HttpMethod.Equals("OPTIONS"))  
    10.     {  
    11.       //通知客户端允许预检请求。并设置缓存时间  
    12.       Response.ClearContent();  
    13.       Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");  
    14.       Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");  
    15.       Response.AddHeader("Access-Control-Allow-Headers", "POWERED-BY-MENGXIANHUI");  
    16.       Response.AddHeader("Access-Control-Max-Age", "30");    
    17.       //此过程无需返回数据  
    18.       Response.End();        
    19.     }  
    20.     else if (Request.HttpMethod.Equals("POST"))  
    21.     {  
    22.       if (Request.Headers["Origin"].Equals("http://www.meng_xian_hui.com:801"))  
    23.       {  
    24.         System.Xml.XmlDocument doc = new System.Xml.XmlDocument();  
    25.         doc.Load(Request.InputStream);  
    26.         Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");  
    27.         Response.Write("您提交的数据是:<br/><br/>" + Server.HtmlEncode(doc.OuterXml));  
    28.       }  
    29.       else  
    30.       {  
    31.         Response.Write("不允许你的网站请求。");  
    32.       }  
    33.     }  
    34.   }  
    35. // --></mce:script>  

    点击“开始测试”按钮,将会执行下面的一系列请求。

    1. OPTIONS /PreflightedRequests.aspx HTTP/1.1
    2. Host: dotnet.aspx.cc
    3. User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
    4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    5. Accept-Language: zh-cn,zh;q=0.5
    6. Accept-Encoding: gzip,deflate
    7. Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
    8. Keep-Alive: 300
    9. Connection: keep-alive
    10. Origin: http://www.meng_xian_hui.com:801
    11. Access-Control-Request-Method: POST
    12. Access-Control-Request-Headers: powered-by-mengxianhui
    13. HTTP/1.x 200 OK
    14. Date: Sun, 10 Jan 2010 14:00:34 GMT
    15. Server: Microsoft-IIS/6.0
    16. X-Powered-By: ASP.NET
    17. X-AspNet-Version: 2.0.50727
    18. Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
    19. Access-Control-Allow-Methods: POST, GET, OPTIONS
    20. Access-Control-Allow-Headers: POWERED-BY-MENGXIANHUI
    21. Access-Control-Max-Age: 30
    22. Set-Cookie: ASP.NET_SessionId=5npqri55dl1k1zvij1tlw3re;path=/; HttpOnly
    23. Cache-Control: private
    24. Content-Length: 0
    25. POST /PreflightedRequests.aspx HTTP/1.1
    26. Host: dotnet.aspx.cc
    27. User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
    28. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    29. Accept-Language: zh-cn,zh;q=0.5
    30. Accept-Encoding: gzip,deflate
    31. Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
    32. Keep-Alive: 300
    33. Connection: keep-alive
    34. POWERED-BY-MENGXIANHUI: Approve
    35. Content-Type: application/xml; charset=UTF-8
    36. Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html
    37. Content-Length: 19
    38. Origin: http://www.meng_xian_hui.com:801
    39. Pragma: no-cache
    40. Cache-Control: no-cache
    41. <root>测试</root>
    42. HTTP/1.x 200 OK
    43. Date: Sun, 10 Jan 2010 14:00:34 GMT
    44. Server: Microsoft-IIS/6.0
    45. X-Powered-By: ASP.NET
    46. X-AspNet-Version: 2.0.50727
    47. Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
    48. Set-Cookie: ASP.NET_SessionId=byvose45zmtbqy45d2a1jf2i;path=/; HttpOnly
    49. Cache-Control: private
    50. Content-Type: text/html; charset=utf-8
    51. Content-Length: 65
    [xhtml] view plain copy
     
     print?
    1. OPTIONS /PreflightedRequests.aspx HTTP/1.1  
    2. Host: dotnet.aspx.cc  
    3. User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)  
    4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
    5. Accept-Language: zh-cn,zh;q=0.5  
    6. Accept-Encoding: gzip,deflate  
    7. Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7  
    8. Keep-Alive: 300  
    9. Connection: keep-alive  
    10. Origin: http://www.meng_xian_hui.com:801  
    11. Access-Control-Request-Method: POST  
    12. Access-Control-Request-Headers: powered-by-mengxianhui  
    13. HTTP/1.x 200 OK  
    14. Date: Sun, 10 Jan 2010 14:00:34 GMT  
    15. Server: Microsoft-IIS/6.0  
    16. X-Powered-By: ASP.NET  
    17. X-AspNet-Version: 2.0.50727  
    18. Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801  
    19. Access-Control-Allow-Methods: POST, GET, OPTIONS  
    20. Access-Control-Allow-Headers: POWERED-BY-MENGXIANHUI  
    21. Access-Control-Max-Age: 30  
    22. Set-Cookie: ASP.NET_SessionId=5npqri55dl1k1zvij1tlw3re; path=/; HttpOnly  
    23. Cache-Control: private  
    24. Content-Length: 0  
    25. POST /PreflightedRequests.aspx HTTP/1.1  
    26. Host: dotnet.aspx.cc  
    27. User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)  
    28. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
    29. Accept-Language: zh-cn,zh;q=0.5  
    30. Accept-Encoding: gzip,deflate  
    31. Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7  
    32. Keep-Alive: 300  
    33. Connection: keep-alive  
    34. POWERED-BY-MENGXIANHUI: Approve  
    35. Content-Type: application/xml; charset=UTF-8  
    36. Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html  
    37. Content-Length: 19  
    38. Origin: http://www.meng_xian_hui.com:801  
    39. Pragma: no-cache  
    40. Cache-Control: no-cache  
    41. <root>测试</root>  
    42. HTTP/1.x 200 OK  
    43. Date: Sun, 10 Jan 2010 14:00:34 GMT  
    44. Server: Microsoft-IIS/6.0  
    45. X-Powered-By: ASP.NET  
    46. X-AspNet-Version: 2.0.50727  
    47. Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801  
    48. Set-Cookie: ASP.NET_SessionId=byvose45zmtbqy45d2a1jf2i; path=/; HttpOnly  
    49. Cache-Control: private  
    50. Content-Type: text/html; charset=utf-8  
    51. Content-Length: 65  

    以上的代码反映了预检请求的执行过程:首先发送 OPTIONS 请求头,用来向服务器咨询服务器的更多信息,以便为后续的真实请求做准备。比如是否支持 POST 方法等。值得注意的是:

    浏览器还发送 Access-Control-Request-Method: POST 和 Access-Control-Request-Headers: powered-by-mengxianhui 请求头。

    注意:以上过程是第一次请求的时候的过程,如果在 30 秒内重复点击按钮,你可以看不到 OPTIONS 这一过程。则执行过程是这样的:

    1. POST /PreflightedRequests.aspx HTTP/1.1
    2. Host: dotnet.aspx.cc
    3. User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
    4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    5. Accept-Language: zh-cn,zh;q=0.5
    6. Accept-Encoding: gzip,deflate
    7. Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
    8. Keep-Alive: 300
    9. Connection: keep-alive
    10. POWERED-BY-MENGXIANHUI: Approve
    11. Content-Type: application/xml; charset=UTF-8
    12. Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html
    13. Content-Length: 19
    14. Origin: http://www.meng_xian_hui.com:801
    15. Pragma: no-cache
    16. Cache-Control: no-cache
    17. <root>测试</root>
    18. HTTP/1.x 200 OK
    19. Date: Sun, 10 Jan 2010 14:06:32 GMT
    20. Server: Microsoft-IIS/6.0
    21. X-Powered-By: ASP.NET
    22. X-AspNet-Version: 2.0.50727
    23. Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
    24. Set-Cookie: ASP.NET_SessionId=qs1c4urxywdbdx55u04pvual;path=/; HttpOnly
    25. Cache-Control: private
    26. Content-Type: text/html; charset=utf-8
    27. Content-Length: 65
    [xhtml] view plain copy
     
     print?
    1. POST /PreflightedRequests.aspx HTTP/1.1  
    2. Host: dotnet.aspx.cc  
    3. User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)  
    4. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
    5. Accept-Language: zh-cn,zh;q=0.5  
    6. Accept-Encoding: gzip,deflate  
    7. Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7  
    8. Keep-Alive: 300  
    9. Connection: keep-alive  
    10. POWERED-BY-MENGXIANHUI: Approve  
    11. Content-Type: application/xml; charset=UTF-8  
    12. Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html  
    13. Content-Length: 19  
    14. Origin: http://www.meng_xian_hui.com:801  
    15. Pragma: no-cache  
    16. Cache-Control: no-cache  
    17. <root>测试</root>  
    18. HTTP/1.x 200 OK  
    19. Date: Sun, 10 Jan 2010 14:06:32 GMT  
    20. Server: Microsoft-IIS/6.0  
    21. X-Powered-By: ASP.NET  
    22. X-AspNet-Version: 2.0.50727  
    23. Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801  
    24. Set-Cookie: ASP.NET_SessionId=qs1c4urxywdbdx55u04pvual; path=/; HttpOnly  
    25. Cache-Control: private  
    26. Content-Type: text/html; charset=utf-8  
    27. Content-Length: 65  

    为什么会这样?细心的童鞋可能注意到了,在服务器端有一行代码 Response.AddHeader("Access-Control-Max-Age", "30"); 它是用来设置预检的有效时间的,单位是秒。这一点要特别注意。

  • 相关阅读:
    sql 积分和消费,类似银行出入账单
    easyui datagrid选中当前行的index
    jquery 1+1=11 纠结死我了
    jquery 选择器
    easyui tree节点设置disabled的功能
    用户体验为什么如此重要?
    三个月内获得三年工作经验
    常用网站
    防呆设计
    读书笔记:启示录,打造用户喜爱的产品
  • 原文地址:https://www.cnblogs.com/susanws/p/5474910.html
Copyright © 2011-2022 走看看