如何将XMLHttpRequest的responseText返回到其他JS函数

时间:2019-11-18 21:50:22

标签: javascript json ajax scope xmlhttprequest

这是我第一次进行Web开发,而我对AJAX,JSON和JavaScript的一般知识仍然非常基础。我想做的是从远程JSON文件中检索和使用数据,并将其导入到我的JavaScript代码的主要功能中。

function getClassData() {
    myReq = new XMLHttpRequest();
    myReq.open('GET', 'https://raw.githubusercontent.com/hexphire/TableTopManager/master/PathOfTheBersekrerBarbarian.json?token=AK3JADKCNBWWGNC7AIE3QZ2526SZ6');
    myReq.onload = function() {
        return JSON.parse(myReq.response);
    }
    myReq.send();
}

但是,当我在主函数中执行console.log时,会得到一个空值。我还尝试在我的主要函数中创建XMLHttpRequest,如下所示:

function myMainFunction (){
let myData = "";
let myReq = new XMLHttpRequest();
myReq.open('GET', 'https://raw.githubusercontent.com/hexphire/TableTopManager/master/PathOfTheBersekrerBarbarian.json?token=AK3JADKCNBWWGNC7AIE3QZ2526SZ6');
myReq.onload = function() {
    myData = JSON.parse(myReq.responseText);
}
console.log(myData);

我的第一个猜测是范围问题,这就是为什么我尝试第二种方法并在onload函数之外声明变量myData的原因,但它仍然显示为null。有什么建议吗?

0 个答案:

没有答案