HTML5 - Web CORS跨域

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

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

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

CORS请求

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

链接:https://www.learnfk.comhttps://www.learnfk.com/html5/html5-cors.html

来源:LearnFk无涯教程网

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

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

技术教程推荐

如何设计一个秒杀系统 -〔许令波〕

消息队列高手课 -〔李玥〕

重学线性代数 -〔朱维刚〕

深入C语言和程序运行原理 -〔于航〕

云原生架构与GitOps实战 -〔王炜〕

手把手教你落地DDD -〔钟敬〕

运维监控系统实战笔记 -〔秦晓辉〕

结构执行力 -〔李忠秋〕

结构沟通力 -〔李忠秋〕

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