使用 Javascript 通过嵌套函数返回数组
Return array back through nested functions with Javascript
大家晚上好。我知道这对这里的许多人来说似乎是一个非常容易的主题,但我一直在努力重建我拥有的功能,以使其在整个站点范围内动态和可重用。
我遇到的主要困难是使用以下方法返回数组:
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()
});
相关文章:
- ES6构造函数返回基类的实例
- 从函数返回角度承诺
- 如何从jquery函数返回变量
- 根据是否解析了 Promise 从函数返回值
- Javascript函数返回未定义
- 如果函数返回True,则显示Javascript按钮
- Google Sheet自定义函数返回0
- 从Ajax函数返回值
- 使用for循环从Javascript中的函数返回多个值
- 谷歌地图:函数返回未定义的值在console.log中运行良好
- 从函数中的函数返回数组时出错
- 如何从嵌套的API函数返回值
- 从Mongoose结果匿名函数返回父函数
- 函数返回错误'令牌{'
- Jquery函数返回订单问题
- Mocha/Chai测试链接到函数返回断言错误
- 从异步函数返回值
- 函数返回后更新变量
- 我如何才能继续'如果'语句来比较作为参数的多个函数返回值
- 将外部函数返回的id传递给内部函数