我想每次加载2条记录"加载更多"使用ajax调用和JSON数据单击按钮。
到目前为止,我一次只能加载一条记录。
这是我的代码:
var loadMoreBtn = $('.load_more');
function loadData() {
var xmlhttp = new XMLHttpRequest();
var url = "jsondata.php";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
var counter = 0;
loadMoreBtn.on('click', function () {
if (counter <= obj.length) {
var out = '';
out += '<ul>';
out += '<li>' + obj[counter]['firtsname'] + ' ' + obj[counter]['lastname'] + '</li>';
$("#results").append(out + '<br/><br/>');
counter++;
}
if (counter >= obj.length) {
loadMoreBtn.attr('disabled', 'disabled')
}
});
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
loadData();
我将不胜感激任何帮助!
答案 0 :(得分:1)
var loadMoreBtn = $('.load_more');
function loadData() {
var xmlhttp = new XMLHttpRequest();
var url = "jsondata.php";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
var counter = 0;
loadMoreBtn.on('click', function () {
//repeat load 'one' two times :) it will load two item if item exists.
for(i =0; i<2; i ++){
if (counter <= obj.length) {
out = '';
out += '<ul>';
out += '<li>' + obj[counter]['firtsname'] + ' ' + obj[counter]['lastname'] + '</li>';
$("#results").append(out + '<br/><br/>');
counter++;
}
if (counter >= obj.length) {
loadMoreBtn.attr('disabled', 'disabled')
}
}
});
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
loadData();