All files / packages/interface-proxy/src jsonp.js

96% Statements 24/25
50% Branches 1/2
100% Functions 4/4
96% Lines 24/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56      8x 8x     8x                 8x       2x   2x 2x 2x 1x 1x     2x 2x 2x 2x 2x 2x       2x 2x 1x         1x 1x   2x 1x     1x      
/**
 * jsonp
 */
import {buildURL} from "../../utils/url";
import {objClone, objCover} from "../../utils/objectOpt";
 
// default ajax params
const defaultOptions = {
    url: '',
    data: null,
    dataType: 'json',
    jsonp: 'callback',
    success: new Function,
    error: new Function,
};
//
let jsonpCounter = 100;
 
export default function ajaxJsonp(config) {
    // init options
    let options = objCover(objClone(defaultOptions), config);
    // create receive func
    let jsonpCallbackName = 'jsonp_cb' + jsonpCounter++;
    let called = false;
    window[jsonpCallbackName] = function (data) {
        called = true;
        options.success(data);
    };
    // script tag
    let pageScript = document.createElement('script');
    pageScript.type = 'text/javascript';
    let params = objClone(options.data);
    params[options.jsonp] = jsonpCallbackName;
    params["_"] = +new Date();
    pageScript.src = buildURL({
        url: options.url,
        params: params
    });
    document.head.appendChild(pageScript);
    pageScript.onload = function () {
        Iif (called === false) {
            options.error({
                message: 'Jsonp response illegal',
            });
        }
        delete window[jsonpCallbackName];
        document.head.removeChild(pageScript);
    };
    pageScript.onerror = function () {
        options.error({
            message: 'Jsonp request error',
        });
        document.head.removeChild(pageScript);
    };
};