这篇文章主要为大家详细介绍了 javascript 跨域资源共享的相关资料,感兴趣的朋友可以参考一下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
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();
- }
来源: http://www.phperz.com/article/17/0304/264480.html