javascript - 尝试使用 XMLHttpRequest 获取 JSON 对象失败并导致引用为空

标签 javascript json functional-programming xmlhttprequest fetch

我正在尝试在 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/

相关文章:

javascript - 在列表中查找带有扩展名的文件名

python - 从嵌套 json 文件中删除 python dict 项

php - JSON 编码/解码无法正常工作

asynchronous - vertx 3 在执行一系列 vertex.fileSytem 操作时避免嵌套 Handler<AsyncResult>

javascript - 如何在不更改上下文的情况下将参数数组传递给函数?

javascript - 如何使用按钮切换嵌套列表

json - 根据其中一个属性删除重复的 JSON 文件

scala - 过滤 (A, Option[B]) 列表并从 Option 中提取值

haskell - 函数式解题: how to use Haskell?

javascript - onchange 事件处理程序触发两次