JSFiddle - React, Tailwind, and code Playground

by fxi

JavaScript

getXML({
  url: 'http://preview.grid.unep.ch/geonetwork/srv/eng/csw?SERVICE=CSW&VERSION=2.0.2&outputSchema=http://www.isotc211.org/2005/gmd&outputFormat=application/xml&REQUEST=GetRecordById&ID=0c6e5849-b73f-4dbd-b83f-8f882823f50f',
  onSuccess: console.log
})

function getXML(o) {
  sendAjax({
    type: 'get',
    url: o.url,
    beforeSend: function(xhr) {
      xhr.setRequestHeader('Accept', 'application/xml');
    },
    onSuccess: function(res) {
      if (res) {
        o.onSuccess(parseXml(res));
      }
    },
    onError: o.onError,
    onComplete: o.onComplete,
    useCache: o.useCache
  });
}

function sendAjax(o) {
  var time = new Date().getTime() + "";
  var timeStr = (o.url.indexOf("?") > 0) ? "&time=" + time : "?time=" + time;
  var xhr = new XMLHttpRequest();
  o.type = o.type ? o.type : "get";
  o.maxWait = o.maxWait ? o.maxWait : 5000; // in ms
  o.useCache = o.useCache === undefined ? window.location.hostname !== "localhost" : o.useCache;
  o.url = o.useCache ? o.url + timeStr : o.url;
  o.onError = o.onError ? o.onError : console.log;
  o.onSuccess = o.onSuccess ? o.onSuccess : console.log;
  o.onComplete = o.onComplete ? o.onComplete : function() {};
  o.beforeSend = o.beforeSend ? o.beforeSend : function() {};
  o.timer = setTimeout(function() { // if xhr won't finish after timeout-> trigger fail
    xhr.abort();
    o.onError();
    o.onComplete();
  }, o.maxWait);
  xhr.open(o.type, o.url);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      clearTimeout(o.timer);
      if (xhr.status === 200 || xhr.status === 0) {
        o.onSuccess(xhr.responseText);
        o.onComplete();
      } else {
        o.onError(xhr.responseText);
        o.onComplete();
      }
    }
  };
  o.beforeSend(xhr);
  xhr.send();
}

function parseXml(xml) {
  var dom = null;
  if (window.DOMParser) {
    try {
      dom = (new DOMParser()).parseFromString(xml, "text/xml");
    } catch (e) {
      dom = null;
    }
  } else if...