asp xmlhttp ajax實現跨網域作業執行個體

來源:互聯網
上載者:User

跨域問題存在實際上源於瀏覽器的同源策略(same origin policy),簡單講,同源就是要求網域名稱,協議,連接埠三者都一致;而同源策略就是指頁面上的指令碼不能訪問非同源的資源(包括http響應和cookie);上面給出了維基百科的地址,如果無法正常訪問請移步這裡:same origin policy

     很多人會想到一個很熟悉的東西:document.domain

    同源策略有點放鬆的就是:b.a.com上的頁面無法通過a.com的同源驗證,但是設定b.a.com頁面的document.domain屬性為a.com,就可以通過瀏覽器對a.com的同源檢測;但是,document.domain只允許設定成更上級的網域名稱,而不是其它網域名稱,例如c.com就不行; 提到這裡很多人都會想到多級網域名稱下共用cookie的路子就是把cooki設定成上級網域名稱;在web2.0的時代,這種本質上同域跨級解決方案遠遠不能滿足我們跨域的需求;

瀏覽器會進行同源檢查,這導致了跨域問題,然而這個跨域檢查還有一個例外那就是html的<script>標記;我們經常使用<script>的src屬性,指令碼靜態資源放在獨立網域名稱下或者來自其它網站的時候這裡是一個url;這個url響應的結果可以有很多種,比如json,返回的json值成為<script>標籤的src屬性值.這種屬性值變化並不會引起頁面的影響.按照慣例,瀏覽器在url的查詢字串中提供一個參數,這個參數將作為結果的首碼一起返回到瀏覽器;

 

調用代碼

<!--#include file="smart.asp教程"-->
<%
response.charset="utf-8"
dim url,method,data,charset
url =request.form("targeturl")
method =request.form("method")
data =request.form("data")
charset = request.form("charset")
if charset = "" then charset = "gb2312"
response.write smarthttp(url,method,data).send().gettext(charset)
set myhttp = nothing
%>

start.asp類檔案

<script language="jscript" runat="server">
/*
在vbs裡面的調用方法
dim myhttp
set myhttp = smarthttp(url,method,data); //三個參數均可選
屬性:
url:string,請求的url地址
method:string,請求的方法
data:string,請求的資料
charset:string,請求的url返回資料的編碼
status:int,請求返回的狀態代碼
readystate:int,同http請求的當前通訊狀態,1、2、3、4
dataset:object,請求的資料,如果增加了,會將這部分資料附加到data屬性
dataset屬性:
charset:string,發送資料的編碼
dataset方法:
append(key,value,noencode):添加資料
remove(key):移除某個資料項目
isexists(key):判斷某個資料項目是不是存在
clear:清除所有資料項目
方法:
header(headstr):佈建要求頭,項和值之間用:分開
timeout(t1,t2,t3,t4):設定逾時時間
send():發送請求
getbinary:擷取伺服器返回的位元據
gettext(charset):擷取指定編碼的文本
getjson(charset):擷取指定編碼的json資料
getheader(key):擷取伺服器返回的回應標頭
getxml(charset):擷取指定編碼的xml資料
*/
function smarthttp(url,method,data){
return new _smarthttp(url,method,data);
}

function _smarthttp(url,method,data){
if(typeof method=="undefined") method="get";
if(typeof data=="undefined") data="";
method = method.touppercase();
method = method!="post" ? "get" : "post";
this.timeout=[10000,10000,10000,10000];
this.method = method;
this.url=url;
this.data=data;
this.charset="gb2312";
this.http=null;
this.headers=[];
this.status=0;
this.readystate=0;
this.content=null;
this.msg="";
this.dataset={
charset:"gb2312",
data:[],
append:function(key,value,noencode){
var fn=null;
if(this.charset.tolowercase()=="utf-8"){fn = encodeuricomponent;}else{fn = escape;}
if(noencode==true){fn=function(_str){return _str;}}
this.data.push({"key":fn(key),"value":fn(value)});
},
remove:function(key){
if(this.data.length<=0) return false;
var _data=[];
for(var i=0;i<this.data.length;i++){
if(this.data[i].key!=key){
_data.push(this.data[i]);
}
}
this.data = _data;
},
isexists:function(key){
if(this.data.length<=0) return false;
for(var i=0;i<this.data.length;i++){
if(this.data[i].key==key){
return true;
}
}
return false;
},
clear:function(){
this.dataset.data=[];
}
};
}

_smarthttp.prototype.init=function(){
var datasetstr="";
if(this.dataset.data.length>0){
for(var i=0;i<this.dataset.data.length;i++){
datasetstr += this.dataset.data[i].key + "=" + this.dataset.data[i].value + "&";
}
}
if(datasetstr!="") datasetstr = datasetstr.substr(0,datasetstr.length-1);
if(this.data==""){this.data = datasetstr;}else{if(datasetstr!="")this.data+= "&" + datasetstr;}
if(this.data=="")this.data=null;
//this.url += ((this.url.indexof("?")<0) ? "?" : "&") + "jornd=" + this.getrnd();
if(this.method=="get" && this.data!=null) this.url += "&" + this.data;
if(this.method=="post") this.headers.push("content-type:application/x-www-form-urlencoded");
if(!this.charset || this.charset=="") this.charset = "gb2312";
};

_smarthttp.prototype.header=function(headstr){
if(headstr.indexof(":")>=0) this.headers.push(headstr);
return this;
};

_smarthttp.prototype.timeout=function(){
if(arguments.length>4){return this;}
for(var i =0;i<arguments.length;i++){
if(!isnan(arguments[i])){
this.timeout[i] = parseint(arguments[i]);
}
}
return this;
};

_smarthttp.prototype.send=function(){
this.init();
var _http = this.getobj();
if(_http==null){return this;}
try{
_http.settimeouts(this.timeout[0], this.timeout[1], this.timeout[2], this.timeout[3]);
}catch(ex){}
_http.open(this.method,this.url,false);
if(this.headers.length>0){
for(var i=0;i<this.headers.length;i++){
var sindex = this.headers[i].indexof(":");
var key = this.headers[i].substr(0,sindex);
var value = this.headers[i].substr(sindex+1);
_http.setrequestheader(key,value);
}
}
_http.send(this.data);
this.readystate = _http.readystate;
if(_http.readystate==4){
this.status = parseint(_http.status);
this.http = _http;
this.content = _http.responsebody;
}
return this;
}

_smarthttp.prototype.getbinary=function(){
return this.content;
};

_smarthttp.prototype.gettext=function(charset){
try{
return this.b2s(this.content,charset ? charset : this.charset);
}catch(ex){
this.msg = ex.description;
return "";
}
};

_smarthttp.prototype.getjson=function(charset){
try{
var _json=null;
eval("_json=(" + this.gettext(charset) + ");");
return _json;
}catch(ex){
this.msg = ex.description;
return null;
}
};

_smarthttp.prototype.getheader=function(key){
if(key){
if(key.touppercase()=="set-cookie"){
key = key.replace("-","-");
var headers = this.http.getallresponseheaders();
var regexp = new regexp("n" + key + ":(.+?)r","ig");
var resstr = "";
while((res = regexp.exec(headers))!=null){
var val = res[1].trim();
resstr = resstr + val.substr(0,val.indexof(";")) + "; "
}
if(resstr!=""){
resstr = resstr.substr(0,resstr.lastindexof(";"));
}
return resstr;
}else{
return this.http.getresponseheader(key);
}
}else{return this.http.getallresponseheaders();}
};

_smarthttp.prototype.getxml=function(charset){
try{
var _dom = new activexobject("msxml2.domdocument");
_dom.loadxml(this.gettext(charset));
return _dom;
}catch(ex){
this.msg = ex.description;
return null;
}
};
_smarthttp.prototype.getobj = function (){
var b=null;
var httplist = ["msxml2.serverxmlhttp.3.0","msxml2.serverxmlhttp","msxml2.xmlhttp.3.0","msxml2.xmlhttp","microsoft.xmlhttp"];
for(var i = 0;i<=httplist.length -1;i++){
try{
b= new activexobject(httplist[i]);
(function(o){
_smarthttp.prototype.getobj = function(){return new activexobject(o)};
})(httplist[i]);
return b;
}catch(ex){
eval("this.msg = ex.description;");
}
}
return b;
};

_smarthttp.prototype.getrnd = function (){return math.random().tostring().substr(2);};

_smarthttp.prototype.b2s = function(bytsource, cset){ //ef bb bf,c0 fd
var objstream,c1,c2,c3;
var byts;
objstream =server.createobject("adodb.stream");
objstream.type = 1;
objstream.mode = 3;
objstream.open();
objstream.write(bytsource);
objstream.position = 0;
objstream.type = 2;
objstream.charset = cset;
byts = objstream.readtext();
objstream.close();
objstream = null;
return byts;
};
_smarthttp.prototype.urlencode=function(str){ return encodeuricomponent(str);};
_smarthttp.prototype.urldecode=function(str){ return decodeuricomponent(str);};
string.prototype.trim = function(){return this.replace(/(^(s+)|(s+)$)/igm,"");};
</script>


總結
跨域請求,顧名思義,就是一個網站中的資源去訪問另外一個不同網域名稱網站上的資源。這種情況很常見,比如說通過 style 標籤載入外部樣式表檔案、通過 img 標籤載入外部圖片、通過 script 標籤載入外部指令檔、通過 webfont 載入字型檔等等。預設情況下,指令碼訪問文件屬性等資料採用的是同源策略(same origin policy)。

那麼,什麼是同源策略呢?如果兩個頁面的協議、網域名稱和連接埠是完全相同的,那麼它們就是同源的。同源策略是為了防止從一個地址載入的文檔或指令碼訪問或者設定從另外一個地址載入的文檔的屬性。如果兩個頁面的主網域名稱相同,則還可以通過設定 document.domain 屬性將它們認為是同源的

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.