跨域资源共享(CORS)是一种允许来自Web浏览器中另一个域的受限资源的机制。
假设,如果您在html5演示部分中单击 HTML5-视频播放器,它将询问相机许可。如果用户允许该权限,则只有它会打开相机,否则不会打开相机。
在这里,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'); }
Sr.No. | Event Handler & Remark |
---|---|
1 | onloadstart 开始请求 |
2 | onprogress 加载数据并发送数据 |
3 | onabort 中止要求 |
4 | onerror 请求失败 |
5 | onload 请求加载成功 |
6 | ontimeout 在请求完成之前发生了超时 |
7 | onloadend 请求完成后,成功或失败 |
xhr.onload=function() { var responseText=xhr.responseText; //处理响应。 console.log(responseText); }; xhr.onerror=function() { console.log('There was an error!'); };
下面的示例将显示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(); }
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)