HTML5 - Web CORS跨域

HTML5 - Web CORS跨域 首页 / HTML5入门教程 / HTML5 - Web CORS跨域

跨域资源共享(CORS)是一种允许来自Web浏览器中另一个域的受限资源的机制。

假设,如果您在html5演示部分中单击 HTML5-视频播放器,它将询问相机许可。如果用户允许该权限,则只有它会打开相机,否则不会打开相机。

CORS请求

在这里,Chrome,Firefox,Opera和Safari都使用XMLHttprequest2对象,而Internet Explorer使用类似的XDomainRequest对象。

function createCORSRequest(method, url) {
   var xhr=new XMLHttpRequest();
   
   if ("withCredentials" in xhr) {
      
      //检查 XMLHttpRequest 对象是否具有“withCredentials”属性。
      //“withCredentials”仅存在于 XMLHTTPRequest2 对象上。
      xhr.open(method, url, true);
   } else if (typeof XDomainRequest != "undefined") {
      
      //否则,检查 XDomainRequest。
      //XDomainRequest 仅存在于 IE 中,是 IE 发出 CORS 请求的方式。
      xhr=new XDomainRequest();
      xhr.open(method, url);
   } else {
      
      //否则,浏览器不支持 CORS。
      xhr=null;
   }
   return xhr;
}

var xhr=createCORSRequest('GET', url);

if (!xhr) {
   throw new Error('CORS not supported');
}

CORS事件

Sr.No.Event Handler & Remark
1

onloadstart

开始请求

2

onprogress

加载数据并发送数据

3

onabort

中止要求

4

onerror

请求失败

5

onload

请求加载成功

6

ontimeout

在请求完成之前发生了超时

7

onloadend

请求完成后,成功或失败

onload or onerror event 示例

xhr.onload=function() {
   var responseText=xhr.responseText;
   
   //处理响应。
   console.log(responseText);
};

xhr.onerror=function() {
   console.log('There was an error!');
};

CORS with handler 示例

下面的示例将显示makeCorsRequest()和onload处理程序

//创建 XHR 对象。
function createCORSRequest(method, url) {
   var xhr=new XMLHttpRequest();
   
   if ("withCredentials" in xhr) {
      
      //XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);
   } else if (typeof XDomainRequest != "undefined") {
      
      //XDomainRequest for IE.
      xhr=new XDomainRequest();
      xhr.open(method, url);
   } else {
      
      //CORS not supported.
      xhr=null;
   }
   return xhr;
}

//从响应中解析标题标签的辅助方法。
function getTitle(text) {
   return text.match('<title>(.*)?</title>')[1];
}

//发出实际的 CORS 请求。
function makeCorsRequest() {
   
   //All HTML5 Rocks properties support CORS.
   var url='http://www.learnfk.com';
   
   var xhr=createCORSRequest('GET', url);
   
   if (!xhr) {
      alert('CORS not supported');
      return;
   }
   
   //响应处理程序。
   xhr.onload=function() {
      var text=xhr.responseText;
      var title=getTitle(text);
      alert('Response from CORS request to ' + url + ': ' + title);
   };
   
   xhr.onerror=function() {
      alert('Woops, there was an error making the request.');
   };
   xhr.send();
}

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

数据结构与算法之美 -〔王争〕

NLP实战高手课 -〔王然〕

系统性能调优必知必会 -〔陶辉〕

爱上跑步 -〔钱亮〕

程序员的个人财富课 -〔王喆〕

全链路压测实战30讲 -〔高楼〕

结构执行力 -〔李忠秋〕

给程序员的写作课 -〔高磊〕

徐昊 · AI 时代的软件工程 -〔徐昊〕

好记忆不如烂笔头。留下您的足迹吧 :)