【问题标题】:Failed on Trying to fetch JSON object using XMLHttpRequest and resulted in empty quotation尝试使用 XMLHttpRequest 获取 JSON 对象失败并导致空引号
【发布时间】: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


    【解决方案1】:

    您使用了异步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

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多