From f0462e3f0b777f38bc6c8049b5e4f9f4f231e6ef Mon Sep 17 00:00:00 2001 From: Alexander Ebert Date: Sun, 24 May 2015 16:00:20 +0200 Subject: [PATCH] Added WoltLab/WCF/Ajax/Jsonp to issue JSONP requests --- .../files/js/WoltLab/WCF/Ajax/Jsonp.js | 68 +++++++++++++++++++ wcfsetup/install/files/js/require.config.js | 1 + 2 files changed, 69 insertions(+) create mode 100644 wcfsetup/install/files/js/WoltLab/WCF/Ajax/Jsonp.js diff --git a/wcfsetup/install/files/js/WoltLab/WCF/Ajax/Jsonp.js b/wcfsetup/install/files/js/WoltLab/WCF/Ajax/Jsonp.js new file mode 100644 index 0000000000..12a7de89ea --- /dev/null +++ b/wcfsetup/install/files/js/WoltLab/WCF/Ajax/Jsonp.js @@ -0,0 +1,68 @@ +/** + * Provides a utility class to issue JSONP requests. + * + * @author Alexander Ebert + * @copyright 2001-2015 WoltLab GmbH + * @license GNU Lesser General Public License + * @module WoltLab/WCF/Ajax/Jsonp + */ +define(['Core'], function(Core) { + "use strict"; + + /** + * @constructor + */ + function AjaxJsonp() {}; + AjaxJsonp.prototype = { + /** + * Issues a JSONP request. + * + * @param {string} url source URL, must not contain callback parameter + * @param {function} success success callback + * @param {function=} failure timeout callback + * @param {object=} options request options + */ + send: function(url, success, failure, options) { + url = (typeof url === 'string') ? url.trim() : ''; + if (url.length === 0) { + throw new Error("Expected a non-empty string for parameter 'url'."); + } + + if (typeof success !== 'function') { + throw new TypeError("Expected a valid callback function for parameter 'success'."); + } + + options = Core.extend({ + parameterName: 'callback', + timeout: 10 + }, options || {}); + + var callbackName = 'wcf_jsonp_' + Core.getUuid().replace(/-/g, '').substr(0, 8); + + var timeout = window.setTimeout(function() { + window[callbackName] = function() {}; + + if (typeof failure === 'function') { + failure(); + } + }, (~~options.timeout || 10) * 1000); + + window[callbackName] = function() { + window.clearTimeout(timeout); + + success.apply(null, arguments); + }; + + url += (url.indexOf('?') === -1) ? '?' : '&'; + url += options.parameterName + '=' + callbackName; + + var script = document.createElement('script'); + script.setAttribute('async', true); + script.setAttribute('src', url); + + document.head.appendChild(script); + } + }; + + return new AjaxJsonp(); +}); diff --git a/wcfsetup/install/files/js/require.config.js b/wcfsetup/install/files/js/require.config.js index e199597822..17a8071165 100644 --- a/wcfsetup/install/files/js/require.config.js +++ b/wcfsetup/install/files/js/require.config.js @@ -6,6 +6,7 @@ requirejs.config({ map: { '*': { 'Ajax': 'WoltLab/WCF/Ajax', + 'AjaxJsonp': 'WoltLab/WCF/Ajax/Jsonp', 'AjaxRequest': 'WoltLab/WCF/Ajax/Request', 'CallbackList': 'WoltLab/WCF/CallbackList', 'Core': 'WoltLab/WCF/Core', -- 2.20.1