【问题标题】:Return JSON from XMLHttpRequest Function从 XMLHttpRequest 函数返回 JSON
【发布时间】:2017-03-12 22:26:02
【问题描述】:

您好,我一直在努力解决从 XMLHttpRequest 函数返回数据的问题。我尝试了许多不同的方法,但是当我尝试从函数外部将数据输出到控制台时,我唯一能得到的就是我总是得到“未定义”。它只有在我从函数本身内部执行时才有效。

<script>
var object;

function loadJSON(path, success, error) {
    var xhr = new XMLHttpRequest();
    var obj1;
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                success(JSON.parse(xhr.responseText));
                //console.log(data); works here!
            } else {
                if (error)
                error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}


object = loadJSON('jconfig.json',
function (data) { console.log(data); return($data);/*works here! but does not return!*/ },
function (xhr) { console.error(xhr); }
);

console.log(object);//does not work here
</script>

我知道这是一个非常简单的问题,但我已经被这个问题困扰了一个多小时,而且其他类似问题的答案似乎无法让我克服这个障碍。非常感谢任何帮助!

编辑:我用一些建议更新了代码,但我仍然无法让 ti 工作。任何建议让上面的代码最终返回我可以在函数之外使用的东西。

【问题讨论】:

  • XHR 是异步的。
  • 我上面的先生说了什么。您的选择是将成功/错误回调传递给 loadJSON 或将本机 XHR 包装在本机/库 Promise 中。
  • 我尝试添加回调,但我似乎仍然无法弄清楚如何返回值。

标签: javascript json xmlhttprequest return


【解决方案1】:

在调用 laodJSON() 函数之后执行 console.log(object) 行,直到那时 JSON 对象才被加载。

这与回调和异步函数有关。您的 loadJSON() 只有在从服务器获得响应时才能真正加载 JSON。

相反,如果要在 loadJSON() 函数之外调用 JSON 对象,则需要使用回调函数。像这样的:

<script>
var object;

function loadJSON(path, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                // Here the callback gets implemented
                object = JSON.parse(xhr.responseText);
                callback();
            } else {

            }
        }
    };

    xhr.open("GET", path, true);
    xhr.send();
    return xhr.onreadystatechange();
}

loadJSON('jconfig.json', function printJSONObject(){
          console.log(object);
    });

// this will not work unless you get the response
console.log(object);

</script>

更新:通过使用回调从异步函数中“返回”一个值是没有意义的,因为下一行代码将立即执行而无需等待响应。

相反,如果您想在发送 XHR 请求的函数之外使用该对象,请在回调函数中实现所有内容。

【讨论】:

  • 感谢您解决这个问题。我想我只是使用 php 来实现同步执行。
  • .. 意思是当 JSON 对象可用时,您将通过 PHP 生成 JavaScript 代码?
猜你喜欢
  • 1970-01-01
  • 2016-12-14
  • 2019-06-02
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多