JSFiddle - React, Tailwind, and code Playground
JavaScript
/**
Fetch data from a URL using window.name as a transport.
@param {string} url
@param {function (string)} callback
@param {?Object.<string>} postData
*/
function fetchData(url, callback, postData) {
/** @type {Element} */
var frame = document.createElement('iframe');
/** @type {Window} */
var frameWin;
/** @type {Document} */
var frameDoc;
/** @type {string} */
var frameName;
/** @type {Element} */
var form;
/** @type {Element} */
var input;
/** @type {string} */
var key;
/**
Send the frame to an accessible location and execute the callback.
*/
function loadRequest() {
frame.onload = function() {
callback(frameWin.name);
frame.parentNode.removeChild(frame);
}
frame.src = 'about:blank';
}
// Give the frame a name to hide it from frames.length
frame.name = frameName = 'fetchData-' + fetchData.fetchCount++;
// Hide frame. Avoid `display:none` to work with old Safari.
frame.style.position = 'fixed';
frame.style.top = frame.style.left = '-10000px';
// If there is post data, create a form in the frame and post it.
if (postData) {
frame.src = 'about:blank';
frame.onload = function() {
frame.onload = loadRequest;
}
document.body.appendChild(frame);
frameWin = frames[frameName];
frameDoc = frameWin.document;
form = frameDoc.createElement('form');
// The form posts to the URL
form.action = url;
// Build form fields from postData
for (key in postData) if (postData.hasOwnProperty(key)) {
input = frameDoc.createElement('input');
input.name = key;
input.value = postData[key];
form.appendChild(input);
}
// Append the form and submit it
frameDoc.body.appendChild(form);
form.submit();
}
// No post...