JSONP代码收藏

摘抄自jQuery,用于JSONP请求。

var callback = 'callback_' + (new Date() - 0),
            url = 'http://localhost/',
            script = document.createElement("script"),
            head = document.head || document.querySelector('head');

        window[callback] = function(data) {
            console.log(data);
            window[callback] = null;
        };

        script.async = true;
        script.charset = 'utf-8';

        script.src = url;

        script.onload = script.onreadystatechange = function( _, isAbort ) {

            if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

                script.onload = script.onreadystatechange = null;

                if ( script.parentNode ) {
                    script.parentNode.removeChild( script );
                }

                script = null;
            }
        };

        head.insertBefore( script, head.firstChild );

 

posted on 2015-03-30 17:59  孤云独去闲  阅读(208)  评论(0编辑  收藏  举报

导航