我正在创建电子书阅读器,现在我想从链接中获取电子书的各个部分:
http://tmaserv.scem.uws.edu.au/chapters/?n=0 It will fetch Section number 0
http://tmaserv.scem.uws.edu.au/chapters/?n=1 It will fetch Section number 1
..
so on
可以从网址http://tmaserv.scem.uws.edu.au/chapters
获取部分数量现在,我可以获取一个部分,但我想要的是读者应该随时在DOM中维护文档的5个部分。我们也只能一次获取一个部分。将获取前5个文档加载,然后根据请求获取其他部分。
代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>EBook</title>
<script>
var requestNum = 0;
// assume I had fetched the number of sections in varibale say sectionCount
function do_exercise () {
var x = new XMLHttpRequest();
// adjust the GET URL to reflect the new n value and request as before
x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=' + requestNum, true);
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status ==200) {
obj = (x.responseText);
JSON.parse(x.responseText);
obj = JSON.parse(obj);
document.getElementById("section1").innerHTML = obj.data;
requestNum++;
}
}
x.send(null);
}
</script>
<body>
<nav>
<button onclick="do_exercise();">Next section</button>
</nav>
<section id = "section1">
</section>
</body>
</html>
我应该使用一些数组来获得5个部分并进行维护吗?
答案 0 :(得分:0)
你想做这样的事吗?
var cacheSize = 5;
var chapters = [];
var requestNum = 0;
function fetchChapter() {
var x = new XMLHttpRequest();
// adjust the GET URL to reflect the new n value and request as before
x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=' + requestNum++, true);
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
obj = (x.responseText);
JSON.parse(x.responseText);
obj = JSON.parse(obj);
chapters.push(obj.data);
if (chapters.length > cacheSize) {
chapters.shift();
}
for (var i = 0; i < chapters.length; ++i) {
document.getElementById("section" + i).innerHTML = chapters[i];
}
}
}
x.send(null);
}