This article mainly shares with you how JS implements browser communication, mainly in the form of code. I hope it can help everyone.
The same-origin policy restricts how documents or scripts loaded from the same source interact with resources from another source. This is an important security mechanism for isolating potentially malicious files. (Three are the same: protocol http/https, domain name and port)
Cookie/LocalStorage and IndexDB cannot be read
DOM cannot be obtained
Ajax request cannot be sent
Result | Reason | |
---|---|---|
Success | |
|
Success | ||
Failed | Different protocols (https and http) | |
Failed | Different ports (81 and 80) | |
Failure | Different domain names (news and store) |
var xht = XMLHttpRequest ? new XMLHttpRequest():new window.ActiveXObject('Microsoft.XMLHTTP');var data = opt.data, url = opt.url, type=opt.type.toUpperCase(), dataArr=[];for(var k in data){ dataArr.push(k+'='+data[k]); }if(type === 'GET'){ url = url + '?' + dataArr.join("&"); xhr.open(type, url.replace(/\?s/g,''), true); xhr.send(); }if(type === 'POST'){ xhr.open(type, url, true); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.send(dataArr.join('&')); } xhr.onload = function(){ if(xhr.status === 200 || xhr.status === 304){ //媒体资源需要206 var res; if(opt.success && opt.success instanceof Function){ res = xhr.responseText; if(typeof res === 'string'){ res = JSON.parse(res); opt.success.call(xhr, res); } } }else{ if(opt.error && opt.error instanceof Function){ opt.error.call(xhr, res); } } }
Description | |
---|---|
Dynamicly create the |
Popular Tutorials
More>
Latest Downloads
More>
|