不使用JQuery实现Jsonp调用

function jsonp_Request(url, data, success, timeout) {
    var finish = false;
    var theHead = document.getElementsByTagName("head")[0] || document.documentElement;
    var scriptControll = document.createElement("script");
    var jsonpcallback = "jsonpcallback" + (Math.random() + "").substring(2);
    var collect = function() {
        if (theHead != null) {
            theHead.removeChild(scriptControll);
            try {
                delete window[jsonpcallback];
            } catch (ex) { }
            theHead = null;
        }
    };
    var init = function() {
        scriptControll.charset = "utf-8";
        theHead.insertBefore(scriptControll, theHead.firstChild);
        window[jsonpcallback] = function(responseData) {
            finish = true;
            success(responseData);
        };
        if (url.indexOf("?") > 0) {
            url = url + "&jsoncallback=" + jsonpcallback;
        } else {
            url = url + "?jsoncallback=" + jsonpcallback;
        }
        if (typeof data == "object" && data != null) {
            for (var p in data) {
                url = url + "&" + p + "=" + escape(data[p]);
            }
        }
    };
    var timer = function() {
        if (typeof window[jsonpcallback] == "function") {
            collect();
        }
        if (typeof timeout == "function" && finish == false) {
            timeout();
        }
    };
    this.request = function() {
        init();
        scriptControll.src = url;
        window.setTimeout(timer, 10000);
    };
}

getJSON = function(url, data, success) { 
    var jsonp = new jsonp_Request(url, data, success); 
    jsonp.request(); 
};
posted @ 2010-07-14 16:44  ahui  阅读(884)  评论(0编辑  收藏  举报