<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> /* * 问题描述: * 我本地http://localhost/cors.html有一需求, * 想要访问外域http://www.lamport.me/domeCROS.php文件怎么办? * <?php * header("Access-Control-Allow-Origin:*"); * echo 'cros'; * ?> * 如果该文件不能访问,你可以在自己的wamp中配置一个虚拟主机进行访问 * 虚拟主机的配置地址: * http://blog.csdn.net/super_yang_android/article/details/53991982 * 首先想到的是cros方法 * */ // 跨浏览器创建并返回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://lamport.me/domeCROS.php"); if (request){ // 用于替代onreadystatechange 检测成功,表示接受数据完毕 request.onload = function(){ // 对响应的信息进行处理 alert(request.responseText); // 取得响应的内容 }; // 用于替代onreadystatechange 检测错误。 request.onerror = function(){ // 对响应的信息进行处理 }; // 用于停止正在进行的请求。 request.onabort = function(){ // 对响应的信息进行处理 alert(request.responseText); }; // 跨域发送请求 request.send(); } </script> </body> </html>
七种跨域方法【1.CROS篇】
猜你喜欢
转载自blog.csdn.net/bobo553443/article/details/80003119
今日推荐
周排行