目前,我正在尝试获取一个包含 javascript 的 html 页面,以从网站检索和显示 JSON,但遇到了一些问题。
用户单击按钮,网站会从 5 个链接检索数据并显示 JSON 中包含的数据。所述数据如下所示:
LINK 0
{ "Genre": "Fantasy", "Title": "Book1" }
LINK 1
{ "Genre": "sciFi", "Title": "Book2"}
首先,我可以检索并显示数据,但我想要的方式是数据不会显示两次。目前我的代码重复 5 次,迭代链接但也显示所有以前的链接,所以我得到这个:
Book1 Book1 Book2 book1 Book2 Book3 book1 Book2 Book3 Book4 Book1 Book1 Book2 book1 Book2 Book3 book1 Book2 Book3 Book4 Book5
当我只想:
Book1 Book2 Book3 Book4 Book5
单击该按钮后,如果再次单击,则应显示接下来 5 个链接的另外 5 部分数据。所以输出应该是:Book6 Book7 Book8 Book9 Book10。
我已经尝试了许多不同的代码变体来解决这个问题,但没有任何效果,而且我尝试修复它的时间越长,我最终变得越困惑。这是我的代码的当前状态:
<html>
<head>
<title>JSON-TEST</title>
<script>
var jnodes = [] ;
var curr_line = 0;
var currentSet = 0;
var endSet = currentSet + 5;
function get_data()
{
request= new XMLHttpRequest();
request.open("GET","http://example.com/",true);
request.onreadystatechange=function()
{
if(request.readyState==4 && request.status==200)
{
var json_no_chapters= JSON.parse(request.responseText);
reply=JSON.parse(request.responseText);
add_nodes(reply);
}
}
request.send()
}
function getsets(page_from,page_to)
{
var i = currentSet;
while (i < endSet)
{
alert('get set '+i); // Can't figure out how to do this without alert. everything falls apart without it.
getset(i);
i++;
}
currentSet = page_to + 1;
endSet = currentSet + 5;
}
function getset(pageno)
{
request= new XMLHttpRequest();
request.open("GET","http://example.com/?pageno="+pageno,true);
request.onreadystatechange=function()
{
if(request.readyState==4 && request.status==200)
{
var json_chapter = JSON.parse(request.responseText);
jnodes.push(json_chapter);
}
}
request.send()
add_nodes(jnodes);
}
function add_nodes(nodesj)
{
var i
for(i=0;i<nodesj.length;i++) // <---- trouble spot I think
{
add_node(nodesj[i]);
}
}
function add_node(nodej)
{
alert(' add node '+nodej.title); // Similar problem with this alert, without it the code works wrong and dont know a way to replace it
var sec=document.createElement("section");
var par=document.createElement("p");
sec.appendChild(par);
par.appendChild(document.createTextNode(nodej.title));
document.getElementById("mydiv").appendChild(sec);
}
</script>
<body>
<header>
<nav><ul>
<li> <input id="nextline" type="button" value="Next Line" /></li>
<li> <input id="prevline" type="button" value="Prev Line" /></li>
</nav></ul>
</header>
<h2> JSON </h2>
<div id="mydiv">
</div>
<input id="button" type="button" value="click" onclick="getsets(currentSet,endSet);" />
</body>
<script>
</script>
</html>
正如我在代码中指出的那样,我遇到的另一个问题是我的代码中有两个警报,但我不知道如何替换它们。如果没有它们,我的代码就会出错,并且会得到错误的输出,例如 Book1 Book1 Book1 Book3 Book5
,但有了它们,警报很快就会变得非常乏味。
非常欢迎任何帮助或建议!
最佳答案
您的 jnodes 是全局的。因此,每次添加节点时,都会打印整个数组。使用计数器来跟踪警报的节点,并且每次只打印最后一个节点而不是整个数组。我希望你能从这里得到它。
关于javascript - JSON数据显示问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23893532/