我正在尝试使用displayItem函数显示数组json中的下一个项目,但是在单击该按钮后,表单将重新加载第一个值(arrayResponse [0])。我该怎么做才能显示下一个项目?
$(document).ready(function () {
var firstElement;
var arrayResponse;
var index = 0;
var request = new XMLHttpRequest();
// When the file has loaded,
request.onload = function () {
// parse the JSON text into an array of post objects.
arrayResponse = JSON.parse(request.responseText);
var firstelement = arrayResponse[0];
$("#name").val(firstelement.name);
$("#author").val(firstelement.author);
$("#content").val(firstelement.content);
// Pass the posts array to the callback.
};
request.open("GET", "http://127.0.0.1:8887/posts.json", true);
request.send(null);
$("#nextButton").bind("click", function () {
displayItem(arrayResponse[++index])
});
function displayItem(item) {
$("#name").val(item.name);
$("#author").val(item.author);
$("#content").val(item.content);
}
});
答案 0 :(得分:1)
我使用此test json
检查了您的代码我创建了this jsfiddle,似乎工作得很完美。你的json肯定会有某种错误。
HTML:
<input id="name" /><br>
<input id="author" /><br>
<input id="content" /><br>
<button id="nextButton">Next</button>
Js:
$(document).ready(function() {
var firstElement;
var arrayResponse;
var index =0;
var request = new XMLHttpRequest();
// When the file has loaded,
request.onload = function () {
// parse the JSON text into an array of post objects.
arrayResponse = JSON.parse(request.responseText);
firstelement = arrayResponse[0];
$("#name").val(firstelement.id);
$("#author").val(firstelement.name);
$("#content").val(firstelement.username);
// Pass the posts array to the callback.
};
request.open("GET", "https://jsonplaceholder.typicode.com/users", true);
request.send(null);
$("#nextButton").bind("click", function(){
displayItem(arrayResponse[++index])
});
function displayItem(item) {
$("#name").val(item.id);
$("#author").val(item.name);
$("#content").val(item.username);
}
});
答案 1 :(得分:0)
改变这个:
$("#nextButton").bind("click", function(){
displayItem(arrayResponse[++index])
});
到此:
$("#nextButton").bind("click", function(){
displayItem(arrayResponse[index]);
index++;
});