尝试引用两个单独的JSON(.txt)文件,其中第二个依赖于第一个的值。成品应该是一个h4标题,下面是“春天”和“(可变)老师的姓氏”。相反,我每次都会列出所有标题h4-s,然后是增加(按一个)数量的值。结果如何:
<first h4>
<second h4>
<third h4>
spring
------
name associated with first h4
<first h4>
<second h4>
<third h4>
spring
------
name associated with first h4
spring
------
name associated with second h4
<first h4>
<second h4>
<third h4>
spring
------
name associated with first h4
spring
------
name associated with second h4
spring
------
name associated with third h4
我认为它可能与getJSON异步有关...这里是javascript:
<script>
$(document).ready(function() {
$.getJSON(("degree.txt"), function(data) {
var courselisting = "";
for (var i in data) {
var teacherfirst = data[i].year.spring.firstname;
var teacherlast = data[i].year.spring.lastname;
courselisting+= '<div class="grid">';
courselisting+= '<div class="col-1-1"><h4 class="ci-header ci-round">' + data[i].course + ', ' + data[i].credits + ' Credit Hour(s)</h4></div>';
$.getJSON(( "/programs/course-information/faculty/" + teacherfirst + teacherlast + ".txt"), function(data) {
var lastname = data.lastname;
var url = data.url;
courselisting+= '<div class="col-1-4"><div class="col-1-3"><p class="small head">Spring<br></p><p class="small"><a id="" class="hlight" href="' + url + '" target="new">' + lastname + '</a></p></div></div></div>';
document.getElementById("schedule-container").innerHTML+=courselisting;
});
};
});
});
</script>
感谢您提供任何帮助!
答案 0 :(得分:1)
您可以强制jQuery等到AJAX调用完成后再使用$ .when执行其他操作。例如,将两个调用包装在两个函数中:
$.when($.getJSON('firstFile.txt')).done(function () {
$.getJSON('secondFile.txt');
doSomethingWithResults();
});
答案 1 :(得分:0)
在循环运行并完成之前,回调将不会运行。在这一点上,courselisting将达到其最终价值。
你可以将它包装在一个闭包中以避免这种情况。
这样的事情:
$(document).ready(function() {
$.getJSON(("degree.txt"), function(data) {
var courselisting = "";
for (var i in data) {
var teacherfirst = data[i].year.spring.firstname;
var teacherlast = data[i].year.spring.lastname;
courselisting+= '<div class="grid">';
courselisting+= '<div class="col-1-1"><h4 class="ci-header ci-round">' + data[i].course + ', ' + data[i].credits + ' Credit Hour(s)</h4></div>';
$.getJSON(( "/programs/course-information/faculty/" + teacherfirst + teacherlast + ".txt"), function(_data,_listing){
innerFunc(_data,_listing);
}(data,courselisting));
};
});
function innerFunc(data,courselisting) {
var lastname = data.lastname;
var url = data.url;
courselisting+= '<div class="col-1-4"><div class="col-1-3"><p class="small head">Spring<br></p><p class="small"><a id="" class="hlight" href="' + url + '" target="new">' + lastname + '</a></p></div></div></div>';
document.getElementById("schedule-container").innerHTML+=courselisting;
}
});