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

封装JSONP

我们经常遇到JS 跨域的问题,跨域的解决方案有很多,JSONP是非常常用的跨域解决方案,这里封装了一下JSONP:

?

function getJSONP(url, callback) {
    if (!url) {
        return;
    }
    var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; //定义一个数组以便产生随机函数名
    var r1 = Math.floor(Math.random() * 10);
    var r2 = Math.floor(Math.random() * 10);
    var r3 = Math.floor(Math.random() * 10);
    var name = 'getJSONP' + a[r1] + a[r2] + a[r3];
    var cbname = 'getJSONP.' + name; //作为jsonp函数的属性
    if (url.indexOf('?') === -1) {
        url += '?jsonp=' + cbname;
    } else {
        url += '&jsonp=' + cbname;
    }
    var script = document.createElement('script');
    //定义被脚本执行的回调函数
    getJSONP[name] = function (e) {
        try {
            //alert(e.name);
        callback && callback(e);
        } catch (e) {
            //
        }
        finally {
            //最后删除该函数与script元素
            delete getJSOP[name];
            script.parentNode.removeChild(script);
        }

    }
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP('http://localhost:8888/',function(response){
  alert(response.name);
});

?

?

服务器端代码:

<?php 
    echo $_GET['jsonp']."({name:'Hi,Kingwell,I come from China',age:20})";
?>

?注:服务器端代码必须是函数名加括号格式,括号里就是JSON格式数据。

?

?

?