javascript - ajax每次点击 "load more"按钮加载2条记录

标签 javascript jquery json ajax

我想使用 ajax 调用和 JSON 数据每次单击“加载更多”按钮时加载 2 条记录。

到目前为止,我能够一次加载一条记录。

这是我的代码:

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();

我将不胜感激任何帮助!

最佳答案

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();

关于javascript - ajax每次点击 "load more"按钮加载2条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32938162/

相关文章:

javascript - 在成功消息之前简单加载

javascript - 嵌入 Google 地球,在卫星 View 中创建网格布局

javascript - 根据特定值按顺序显示数组中的对象

javascript - 使用 Watij 测试 jQuery 更改事件

json - 使用换行符渲染 json 数据flask/jinja2

javascript - 如何访问从 AJAX 响应返回的 JSON 数组元素

Java/Android JSON 请求不更新收到的数据

javascript - 使用 j 查询在一个下拉列表中选择选项时如何填充 json?

javascript - 使用 Node js Azure 函数将消息上的自定义属性发送到服务总线主题

jquery - 使用 jQuery prop() 按名称添加 html 实体