Skip to content

Instantly share code, notes, and snippets.

@chenwery
Last active August 29, 2015 14:01
Show Gist options
  • Save chenwery/f82cd876b5b4ffe4fb58 to your computer and use it in GitHub Desktop.
Save chenwery/f82cd876b5b4ffe4fb58 to your computer and use it in GitHub Desktop.
跨域解决方法
//parse and organize all QS parameters in a more comfortable way
var params = {};
if (location.search.length > 1) {
var i, arr = location.search.substr(1).split("&");
for (i = 0; i < arr.length; i++) {
arr[i] = arr[i].split("=");
params[arr[i][0]] = unescape(arr[i][1]);
}
}
//support server answer as JavaScript Object-Literals or JSON:
// evaluate the data expression
try {
eval("params.data = " + params.data);
} catch (e) {
params.data = {error: "server response failed with evaluation error: " + e.message
,data : params.data
}
}
//invoke the callback on the parent
try{
window.parent[ params.callback ](params.data || "no-data-returned");
}catch(e){
//if something went wrong - at least let's learn about it in the
// console (in addition to the timeout)
throw "Problem in passing POST response to host page: \n\n" + e.message;
}
8种情况跨域解决方法:
---------------------------------------------
JSONP法(最常见)
---------------------------------------------
iframe(document.domain)法:a.site.com b.site.com
document.domain = site.com
a.site.com用iframe嵌套b.site.com可读取contentWindow或contentDocument
---------------------------------------------
hash法
a.com嵌套b.com,b.com嵌套a.com
就可以在最下层的a.com中访问到parent.parent.document/parent.parent/window
parent.parent.location.hash = self.location.hash.substring(1)
---------------------------------------------
HTML5 postMessage法(重点)
---------------------------------------------
flash法
---------------------------------------------
window.name法(难点)
---------------------------------------------
XMLHttpRequest Level 2(重点)Access-Control-Allow-Origin:*
---------------------------------------------
提交form的数据到异域或https:
form的target设置为页面中的一个隐藏的iframe
<form target="hidden-iframe-id"></form>
<iframe id="hidden-iframe-id"></iframe>
iframe中的页面redirect回原域的一个页面,并把callback之类的信息带到URL中,在这个iframe种访问parent执行callback
http://stackoverflow.com/questions/5345493/using-put-post-delete-with-jsonp-and-jquery
//declare the Async-call callback function on the global scope
function myAsyncJSONPCallback(data){
//clean up
var e = document.getElementById(id);
if (e) e.parentNode.removeChild(e);
clearTimeout(timeout);
if (data && data.error){
//handle errors & TIMEOUTS
//...
return;
}
//use data
//...
}
var serverUrl = "http://crossdomain.com/server/page",
params = {
param1 : "value of param 1", //I assume this value to be passed
param2 : "value of param 2", //here I just declare it...
callback: "myAsyncJSONPCallback"
},
clientUtilityUrl = "http://samedomain.com/utils/postResponse.html",
id = "some-unique-id", // unique Request ID. You can generate it your own way
div = document.createElement("DIV"),//this is where the actual work start!
HTML = [
"<IFRAME name='ifr_",id,"'></IFRAME>",
"<form target='ifr_",id,"' method='POST' action='",serverUrl, "' id='frm_",id,"' enctype='multipart/form-data'>"
],
each, pval, timeout;
//augment utility func to make the array a "StringBuffer" - see usage bellow
HTML.add = function(){
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i];
}
};
//add rurl to the params object - part of infrastructure work
params.rurl = clientUtilityUrl; //ABSOLUTE URL to the utility page must be on
//the SAME DOMAIN as page that makes the request
//add all params to composed string of FORM and IFRAME inside the FORM tag
for(each in params){
pval = params[each].toString().replace(/\"/g,"&quot;");//assure: that " mark will not break
HTML.add("<input name='",each,"' value='",pval,"'/>"); // the composed string
}
//close FORM tag in composed string and put all parts together
HTML.add("</form>");
HTML = HTML.join(""); //Now the composed HTML string ready :)
//prepare the DIV
div.id = id; // this ID is used to clean-up once the response has come, or timeout is detected
div.style.display = "none"; //assure the DIV will not influence UI
//TRICKY: append the DIV to the DOM and *ONLY THEN* inject the HTML in it
// for some reason it works in all browsers only this way. Injecting the DIV as part
// of a composed string did not always work for me
document.body.appendChild(div);
div.innerHTML = HTML;
//TRICKY: note that myAsyncJSONPCallback must see the 'timeout' variable
timeout = setTimeout("myAsyncJSONPCallback({error:'TIMEOUT'})",4000);
document.getElementById("frm_"+id+).submit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment