【发布时间】:2019-01-13 22:23:57
【问题描述】:
我正在尝试在 Javascript 中使用 XMLHttpRequest 获取和解析 JSON-Object,但它总是失败并导致空引号...
function getJSON(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)));
}
用法:
getJSON('localhost/logs.json');
预期结果:
["John eaten the cake","Stackoverflow is awesome"]
当前结果:
""
【问题讨论】:
标签: javascript json functional-programming xmlhttprequest fetch