js跨域资源共享 基础篇


本文详细介绍了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/aaa/dome2.php");
  if (request){
    // 用于替代onreadystatechange 检测成功,表示接受数据完毕
    request.onload = function(){
      // 对响应的信息进行处理
      alert(request.responseText);  // 取得响应的内容
    };
    // 用于替代onreadystatechange 检测错误。
    request.onerror = function(){
      // 对响应的信息进行处理
    };
    // 用于停止正在进行的请求。
    request.onabort = function(){
      // 对响应的信息进行处理
      alert(request.responseText);
    };
    // 跨域发送请求
    request.send();
  }

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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3