js跨域资源共享 基础篇

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js跨域资源共享 基础篇

光明大神棍   2020-05-15 我要评论

本文详细介绍了javascript跨域资源共享,供大家参考,具体内容如下

1.为什么提出跨域资源共享(CORS)?
    因为XHR实现ajax的安全限制是:XHR 对象只能访问与包含它的页面位于同一个域中的资源

2.如何实现跨域?(跨浏览器)

  // 跨浏览器创建并返回CORS对象
  // param method : 请求的方式, get or post
  // param url : 跨域请求的url
  // return xhr : 返回的跨域资源对象
  function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr){
      xhr.open(method, url, true);  // CORS都是通过异步的请求
    } else if (typeof XDomainRequest != "undefined"){  // IE
      vxhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      xhr = null;
    }
    return xhr;
  }
  var request = createCORSRequest("get", "http://localhost/aaahttps://img.qb5200.com/download-x/dome2.php");
  if (request){
    // 用于替代onreadystatechange 检测成功,表示接受数据完毕
    request.onload = function(){
      // 对响应的信息进行处理
      alert(request.responseText);  // 取得响应的内容
    };
    // 用于替代onreadystatechange 检测错误。
    request.onerror = function(){
      // 对响应的信息进行处理
    };
    // 用于停止正在进行的请求。
    request.onabort = function(){
      // 对响应的信息进行处理
      alert(request.responseText);
    };
    // 跨域发送请求
    request.send();
  }

以上就是本文的全部内容,希望对大家的学习有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们