My attempts to Fetch and Parse a JSON Object using XMLHttpRequest in Javascript are always unsuccessful, resulting in an empty quotation...
function fetchAndParseJSON(target = null)
{
var response_data = [];
var target_url = target;
var xhr = new XMLHttpRequest();
xhr.open('GET', target_url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
xhr.addEventListener("readystatechange", function ()
{
if(xhr.readyState === 4)
{
if(xhr.status >= 200 && xhr.status < 304)
{
response_data += xhr.response;
}
else
{
response_data += $.getJSON(target_url);
console.log('[XHR-DEBUG]: Unexpected HTTP response code: ' + xhr.status + ': ' + xhr.statusText + '(' + target_url + ')');
}
}
});
return JSON.parse(JSON.stringify((typeof response_data === 'undefined' || response_data === null || response_data.toString().split(',').length <= 1 ? xhr.response : response_data)));
}
Usage:
fetchAndParseJSON('localhost/logs.json');
Expected output:
["John eaten the cake","Stackoverflow is awesome"]
Result obtained:
""