使用 Javascript 通过嵌套函数返回数组

Return array back through nested functions with Javascript

本文关键字:函数 返回 数组 嵌套 Javascript 使用      更新时间:2023-09-26

大家晚上好。我知道这对这里的许多人来说似乎是一个非常容易的主题,但我一直在努力重建我拥有的功能,以使其在整个站点范围内动态和可重用。

我遇到的主要困难是使用以下方法返回数组:

var arr = getData("admin/fullDatabaseAccess.php");

这不会按预期返回数组。现在,在不编写我对 getData 函数所做的所有可能的变体以尝试返回它创建的数组的情况下,我将首先向您展示有效的原始函数:

function getData() {
var xmlhttp = new XMLHttpRequest();
var url = "admin/fullDatabaseAccess.php";
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        processResponse(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {

    var arr = JSON.parse(response);
    // do stuff with the array - I originally modified the DOM using jQuery here, however I now want to use this entire getData function as a more generically useful function
    }
}

然后,我将在使用此代码生成数组的单个页面上触发 getData 函数,然后使用数组数据修改页面元素。

这让我想到了我的问题 - 我试图通过在下面创建此版本并使用我最初发布的代码行调用数组数据(var arr = ..(来使这个函数在整个站点中可重用:

function getData(file) {
var xmlhttp = new XMLHttpRequest();
var url = file;
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        processResponse(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
    var arr = JSON.parse(response);

    return arr;

}

}

我似乎无法将数据反馈给变量。我已经尝试了很多重组函数以返回嵌套等中的值,但是我已经到了让自己感到困惑的地步,并且无法真正显示我尝试过的示例,因为我删除了它们并决定重新开始。

任何帮助将不胜感激!

你需要提供一个回调getData,像这样

function getData(file, cb) {
  var xmlhttp = new XMLHttpRequest();
  var url = file;
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      // Calls the callback function with the response data
      cb(processResponse(xmlhttp.responseText));
    }
  }
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
  function processResponse(response) {
    var arr = JSON.parse(response);
    return arr;
  }
}
getData(file, function(data) {
  // data is now what's being returned from processResponse()
});