Jump to content

Recommended Posts

Posted (edited)

Using JSON-P for cross-domain and Promises. This is kind of an old approach to CORS, but still kind of around when the likes of IE 9 is being used.

/*global console, Promise*/

var jsonp = (function jsonpModule(window, document, Object, Promise, encodeURIComponent, setTimeout) {
    var _api = {
        get: get,
    };
    var _id = 0;
    var _noop = function noop() {};

    return _api;

    /**
     * Simple JSON-P implementation
     */
    function get(url, params) {
        params = params || {};

        var error = _noop;
        var success = _noop;

        var promise = new Promise(function promise(resolve, reject) {
            success = resolve;
            error = reject;
        });

        // Required because of the timeapi stripping the original design of using an internal object and dot notation. It stripped the dots!
        var callback = 'jsopGet' + _id++;

        // Extend with the (optional) callback function parameter
        var extend = {};
        extend[params.callback || 'callback'] = callback;
        params = Object.assign(params, extend);

        // Create the query parameter string
        var queryString = '?' + Object.keys(params).map(function mapKeys(key) {
            return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
        }).join('&');

        // Create script element
        var script = document.createElement('script');
        script.async = true;
        script.src = url + queryString;

        // Set callback function(s)
        script.addEventListener('error', function errorEvent() {
            _destroy();
            error();
        });

        window[callback] = function successEvent(response) {
            _destroy();
            success(response);
        };

        // Inject script
        setTimeout(function setTimeout() {
            document.head.appendChild(script);
        }, 0);

        return promise;

        // Destroy the JSON-P callback function and script element node
        function _destroy() {
            window[callback] = _noop;
            script.parentNode.removeChild(script);
        }
    }
}(
    window,
    document,
    Object,
    Promise,
    encodeURIComponent,
    setTimeout
));

jsonp.get('http://www.timeapi.org/utc/now.json').then(function success(response) {
    console.log(response.dateString);
}).catch(function error() {
    console.log('An error occurred. As to what that error was, it\'s hard to determine using JSON-P');
});

 

Edited by guinness

UDF List:

  Reveal hidden contents

Updated: 22/04/2018

Posted

Added optional callback param, to set the callback query parameter name e.g. cb=jsonpGet0

UDF List:

  Reveal hidden contents

Updated: 22/04/2018

Posted
  On 6/4/2016 at 10:16 PM, guinness said:

// Destroy the JSON-P csllback function and script element node

Expand  

Did you mean "callback" ?

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

  Reveal hidden contents

Signature last update: 2023-04-24

Posted
  On 6/5/2016 at 3:02 PM, mLipok said:

Did you mean "callback" ?

Expand  

I did indeed. Thanks.

UDF List:

  Reveal hidden contents

Updated: 22/04/2018

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...