JSFiddle - React, Tailwind, and code Playground
by kmturley
JavaScript
// ajax function
function ajax(url, callback, filetype, type) {
filetype = filetype ? filetype : 'json';
type = type ? type : 'GET';
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
var success = function(e) {
var items = '';
switch(filetype) {
case 'csv': items = csv(xhr.responseText); break;
case 'json': items = JSON.parse(xhr.responseText); break;
default: items = xhr.responseText; break;
}
callback(items);
}
var error = function(e) { console.log('Please enabled CORS using access-control-allow-origin'); }
if (window.XDomainRequest && !sameOrigin(url)) { xhr = new XDomainRequest(); xhr.onload = success; }
if (filetype == 'image' && xhr.overrideMimeType) { xhr.overrideMimeType('text/plain; charset=x-user-defined'); }
xhr.onerror = error;
xhr.onreadystatechange = function(e) { if (xhr.readyState == 4 && xhr.status == 200) { success(e); } }
try {
if ('withCredentials' in xhr) { xhr.open(type, url, true); }
else { xhr.open(type, url); }
xhr.send(null);
}
catch(e) { error(e); }
}
// check if url is same domain
function sameOrigin(url){
var split = url.split('/');
if (split[0]+'//' == window.location.protocol+'//') { return split[2] != window.location.host ? false : true; }
else { return true; }
}
// calculate length of object
function size(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
}
// convert string to csv
function csv(string, divider) {
divider = divider || ',';
var regex = new RegExp(("(\\"+divider+"|\\r?\\n|\\r|^)"+"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +"([^\"\\"+divider+"\\r\\n]*))"), 'gi');
var regex2 = new RegExp("\"\"", 'g');
var items = [];
var fields = [];
var matches = null;
while (matches = regex.exec(string)) {
var match = matches[1];
...