Javascript 仅通过一个Success侦听器通过config使用ajax加载未定义数量的文件内容
我有一个json配置,它有一个包含文件名的对象数组。我需要将它们装入一行,并在所有文件都已准备好装入并在我的主页上以代码段的形式显示它们时生成一个事件 config.json:Javascript 仅通过一个Success侦听器通过config使用ajax加载未定义数量的文件内容,javascript,jquery,ajax,typescript,ecmascript-6,Javascript,Jquery,Ajax,Typescript,Ecmascript 6,我有一个json配置,它有一个包含文件名的对象数组。我需要将它们装入一行,并在所有文件都已准备好装入并在我的主页上以代码段的形式显示它们时生成一个事件 config.json: { "author": "TypedSource", "date": "2017-04-16", "files": [ { "lang": "HTML", "fileName": "sample.html.txt" }, { "lang": "PHP
{
"author": "TypedSource",
"date": "2017-04-16",
"files": [
{
"lang": "HTML",
"fileName": "sample.html.txt"
},
{
"lang": "PHP",
"fileName": "sample.php.txt"
},
]
}
打字脚本代码:
$(document).ready(function(){
$.get('config.json')
.ready(function(data){
console.log('success on loading config');
$.when(
// i want to load every file here
// but this for can't work inside the $.when
// it is just pseudo code for explain what i want to do
for(let i = 0; i < data.files.length; i++) {
$.get(data.files[i].fileName);
}
}.then(
function(){
// success listener for all files loaded
console.log('success on loading all files');
console.log(arguments);
// now build the template for each response[0] and bind it to highlight.js code block
}
function(){
// error listener if a file can't be loaded
// ATTENTION: if an error occured, no single success is given
console.error('error on loading files');
console.log(arguments[0].responseText());
}
)
})
.fail(function(){
console.error('error on loading config file');
console.log(arguments[0].responseText);
});
});
$(文档).ready(函数(){
$.get('config.json')
.就绪(功能(数据){
log(“加载配置成功”);
美元。什么时候(
//我想在这里加载每个文件
//但是这个在$内不起作用。什么时候
//这只是解释我想做什么的伪代码
for(设i=0;i
$.get只接受一个url来加载,$。我知道的选项是when,但通常我必须手动分配when中的每个调用。有人知道如何处理它吗?创建一个要传递的请求承诺数组,直到所有请求承诺都得到解决后才会解析
$.getJSON('config.json').then(function(config) {
var requests = config.files.map(function(file) {
return $.get(file.fileName);
});
Promise.all(requests).then(function(res) {
console.log(res)
res.forEach(function(txt) {
$('body').append('<p>' + txt + '</p>')
});
});
});
$.getJSON('config.json')。然后(函数(config){
var requests=config.files.map(函数(文件){
返回$.get(file.fileName);
});
承诺。所有(请求)。然后(函数(res){
console.log(res)
res.forEach(函数(txt){
$('body')。追加(''+txt+'')
});
});
});
Promise.all()中结果数组的顺序将与配置文件中的文件数组顺序相同
如果可能的话,我不想为每个文件生成一个请求,并编写一个包装侦听器来检查成功的ajax调用的数量是否与文件数组中的条目数相同。像这样的行是我想要的,但我得到一个更透明的错误:
错误:(83,25)TS2693:“Promise”仅引用类型,但在此处用作值。
Promise是浏览器中的窗口属性…不确定使用的是哪个transpiler…可以尝试window.Promise.all()
错误:(84,32)TS2339:类型“Window”上不存在属性“Promise”。Window
是小写。应该可以轻松搜索如何在typescript中使用Window
。我个人不使用typescript muchi找到了解决方案,这是一个ts配置问题。编译器选项:{“模块”:“commonjs”,“目标”:“es5”,“sourceMap”:true,“outFile”:“./public_html/js/ts.js”,“lib”:[“dom”,“es2015”,“es5”,“es6”]},
将lib条目添加到tsconfig.json解决了它。