ASP XMLHTTP AJAX Implementation cross-domain operation instance

Source: Internet
Author: User
Tags eval gettext http request json script tag trim

The Cross-domain problem exists in fact originated from the browser's homology strategy (same origin policy), in brief, homology is the request domain name, the protocol, the port three all are consistent, but the homologous policy means that the script on the page cannot access the resources that are not homologous (including HTTP response and cookie); Above gives the address of Wikipedia, if not normal access please visit here: Same origin policy

A lot of people think of something very familiar: Document.domain

Homologous strategy a bit relaxed is: b.a.com on the page can not pass the A.com authentication, but set the b.a.com page document.domain attribute to a.com, you can through the browser to the a.com of homology detection; Document.domain only allowed to set up a higher level of domain names, rather than other domain names, such as c.com; Mention here a lot of people will think of multi-level domain name to share the cookie path is to set the Cooki to the superior domain name; In the era of web2.0, this kind of domain-wide cross-domain solution is far from satisfying our cross-domain needs;

The browser makes a homology check, which causes cross-domain problems, but there is an exception to this cross-domain check: HTML <script> tags; we often use the SRC attribute of <script>, Script static resources are placed under separate domain names or from other sites here is a URL; The URL can respond with a variety of results, such as JSON, and the returned JSON value becomes a <script> The SRC attribute value of the label. This property value change does not cause the page to be affected. By convention, the browser provides a parameter in the URL's query string that returns to the browser as the prefix of the result;

Calling code

<!--#include file= "smart.asp Tutorial"-->
<%
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 class file

<script language= "JScript" runat= "Server" >
/*
Calling methods inside the VBS
Dim myhttp
Set myhttp = Smarthttp (Url,method,data); Three parameters are optional
Property:
url:string, URL address of the request
Method:string, the method of the request
Data:string, requested data
Charset:string, the requested URL returns the encoding of the data
Status:int, request the returned status code
Readystate:int, current communication status with HTTP request, 1, 2, 3, 4
Dataset:object, the requested data is appended to the Data property if it is added
DataSet Properties:
charset:string, encoding of data sent
DataSet method:
Append (Key,value,noencode): Adding data
Remove (Key): Remove a data item
Isexists (Key): Determine if a data item exists
Clear: Clears all data items
Method:
Header (HEADSTR): Set request headers, between items and values by: separating
Timeout (T1,T2,T3,T4): Setting timeout time
Send (): Sending request
Getbinary: Gets the binary data returned by the server
GetText (CharSet): Gets the specified encoded text
Getjson (CharSet): Gets the specified encoded JSON data
GetHeader (Key): Gets the response headers returned by the server
Getxml (CharSet): Gets the specified encoded XML data
*/
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>


Summarize
Cross-domain requests, as the name suggests, are resources in one site to access resources on another different domain name site. This is common, such as loading an external style sheet file with a style tag, loading an external picture via an IMG tag, loading an external script file with a script tag, loading a font file by Webfont, and so on. By default, data such as script access to document properties are based on homology policies (same origin policy).

So, what is a homology strategy? If the two-page protocol, domain name, and port are exactly the same, then they are homologous. The homology policy is intended to prevent access to documents or scripts loaded from one address or to set properties of documents loaded from another address. If two pages have the same primary domain name, they can also be considered homologous by setting the Document.domain property

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.