我正在尝试在 Javascript 中使用 XMLHttpRequest 获取和解析 JSON 对象,但它总是失败并导致空引号...
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"]
当前结果:
""
最佳答案
您使用了异步 XMLHttpRequest
。所以问题出在以下行:
return JSON.parse(JSON.stringify((typeof response_data === 'undefined' || response_data === null || response_data.toString().split(',').length <= 1 ? xhr.response : response_data)));
这被放置在事件监听器之外,当该行运行时数据不可用。
要使其正常工作,请使用同步 XMLHttpRequest
(不推荐):
xhr.open('GET',target_url,false)
或者使用异步/等待:
async 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');
await new Promise((resolve,reject)=>{
xhr.addEventListener("readystatechange", function ()
{
if(xhr.readyState === 4)
{
if(xhr.status >= 200 && xhr.status < 304)
{
response_data.push(xhr.response);
}
else
{
response_data.push(await getJSON(target_url));
console.log('[XHR-DEBUG]: Unexpected HTTP response code: ' + xhr.status + ': ' + xhr.statusText + '(' + target_url + ')');
}
resolve()
}
});
xhr.send()
});
return JSON.parse(JSON.stringify((typeof response_data === 'undefined' || response_data === null || response_data.length <= 1 )? xhr.response : response_data));
}
另见:
Async function
Promise
Await operator
希望对您有所帮助!
关于javascript - 尝试使用 XMLHttpRequest 获取 JSON 对象失败并导致引用为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54169263/