解決AJAX中跨域訪問出現'沒有權限'的錯誤
2024-05-06 14:17:24
供稿:網友
禁止訪問非同域的網站,下面一個例子來訪問http://www.google.cn,
<script type="text/javascript">
function createobj() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
}
function getWebPage(url) {
var oBao=createobj();
var my_url=url
oBao.open('get',my_url,false);
oBao.onreadystatechange=function(){
if(oBao.readyState==4){
if(oBao.status==200){
var returnStr=oBao.responseText;
document.write(returnStr);
}else{
document.write("未找到您輸入的地址或服務器505錯誤!");
}
}
}
oBao.send(null);
}
getWebPage('http://www.google.cn');
</script>
保存這段代碼到test.html,在本地直接用IE打開沒問題,但將該段代碼上傳到服務器后,問題出現了--JS提示"沒有權限"錯誤!!!這該如何解決呢?
下面思考一下:既然不能訪問非同域的,只能訪問同域的地址了,同域的動態文件怎么獲取非同域網頁內容呢?我們還是想到的AJAX,只不過這個AJAX是在服務器端執行.
大體思路是這樣的:首先將URL用AJAX提交給自己站內的文件,例如getPage.asp---在getPage.asp再次通過服務器XMLHTTP來訪問提交來的URL---將獲取的內容返回給提交URL的頁----顯示內容
下面開始組織代碼,首先是test.html文件
<script type="text/javascript">
function createobj() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
}
function getWebPage(url) {
var oBao=createobj();
var my_url="getpage.asp?url="+escape(url);
oBao.open('get',my_url,false);
oBao.onreadystatechange=function(){
if(oBao.readyState==4){
if(oBao.status==200){
var returnStr=oBao.responseText;
document.write(returnStr);
}else{
document.write("未找到您輸入的地址或服務器505錯誤!");
}
}
}
oBao.send(null);
}
getWebPage('http://www.google.cn');
</script>
再就是getpage.asp文件(注意:要以UTF-8格式保存本文件,防止亂碼),如下:
<%
response.charset="UTF-8"
reg="/<meta.+ charset= {0,}([^/"" />//]*).+//{0,1}/>"
'函數名:GetResStr
'作用:獲取指定URL的HTML代碼
'參數:URL-要獲取的URL
function GetResStr(URL)
err.clear
dim ResBody,ResStr,PageCode,ReturnStr
Set Http=createobject("MiCROSOFT.XMLHTTP")
Http.open "GET",URL,False
Http.Send()
If Http.Readystate =4 Then
If Http.status=200 Then
ResStr=http.responseText
ResBody=http.responseBody
PageCode=GetCode(ResStr,reg)
ReturnStr=BytesToBstr(http.responseBody,PageCode)
GetResStr=ReturnStr
End If
End If
End Function
'函數名:BytesToBstr
'作用:轉換二進制數據為字符
'參數:Body-二進制數據,Cset-文本編碼方式