日期:2014-05-16  浏览次数:20312 次

纯js实现 跨域请求
1.一个封装的例子
$$ = function(win){
var isIE = !-[1,];
doc = win.document;
head = doc.getElementsByTagName('head')[0];
function request(url, success, timestamp){
var script = doc.createElement('script');
function callback(){
if(typeof jsonp != 'undefined'){
success(jsonp);
}else{
//success("");
//alert('warning: jsonp did not return.');
alert("Shopalと通信ができません");
}
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if( head && script.parentNode ){
head.removeChild(script);
}
}
if(isIE){
script.onreadystatechange = function(){
var readyState = this.readyState;
if(readyState == 'loaded' || readyState == 'complete'){
callback();
}
};
}else{
script.onload = function(){
callback();
};
}
if(timestamp){
url += '?ts=' + (new Date).getTime();
}
script.src = url;
head.insertBefore(script, head.firstChild);
}
return {load:request};
}(this);

----------------------------
原理:

    <script type="text/javascript">
    // This is our function to be called with JSON data
    function showPrice(data) {
        alert("Symbol: " + data.symbol + ", Price: " + data.price);
    }
    var url = “ticker.js”; // URL of the external script
    // this shows dynamic script insertion
    var script = document.createElement('script');
    script.setAttribute('src', url);

    // load the script
    document.getElementsByTagName('head')[0].appendChild(script);
    </script>




http://club.topsage.com/thread-327033-1-1.html