跨域-CROS

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>

/*
* 問(wèn)題描述:
* 我本地http://localhost/cors.html有一需求,
* 想要訪(fǎng)問(wèn)外域http://www.lamport.me/domeCROS.php文件怎么辦?
* <?php
* header("Access-Control-Allow-Origin:*");
* echo 'cros';
* ?>
* 如果該文件不能訪(fǎng)問(wèn),你可以在自己的wamp中配置一個(gè)虛擬主機(jī)進(jìn)行訪(fǎng)問(wèn)
* 虛擬主機(jī)的配置地址:
* http://blog.csdn.net/super_yang_android/article/details/53991982
* 首先想到的是cros方法
* */


// 跨瀏覽器創(chuàng)建并返回CORS對(duì)象
// param method : 請(qǐng)求的方式, get or post
// param url : 跨域請(qǐng)求的url
// return xhr : 返回的跨域資源對(duì)象
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true); // CORS都是通過(guò)異步的請(qǐng)求
} 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 檢測(cè)成功,表示接受數(shù)據(jù)完畢
request.onload = function(){
// 對(duì)響應(yīng)的信息進(jìn)行處理
alert(request.responseText); // 取得響應(yīng)的內(nèi)容
};
// 用于替代onreadystatechange 檢測(cè)錯(cuò)誤。
request.onerror = function(){
// 對(duì)響應(yīng)的信息進(jìn)行處理
};
// 用于停止正在進(jìn)行的請(qǐng)求。
request.onabort = function(){
// 對(duì)響應(yīng)的信息進(jìn)行處理
alert(request.responseText);
};
// 跨域發(fā)送請(qǐng)求
request.send();
}


</script>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容