javascript - AJAX 仅加载和返回有限数量的对象

标签 javascript ajax count return-value

我刚刚开始使用 AJAX,我想知道是否可以指定 AJAX 调用应返回的对象数量。

为了测试,我从 here 创建了一个 JSON.db 文件。 .

我的代码如下所示(使用 Polymer Web 组件):

HTML:

<body>
  <h1>Object-list</h1>
  <template is="dom-bind">
    <evo-object_list>
    </evo-object_list>
  </template>
  <h1 id = 'loadInHere'></h1>
  <button onclick = 'loadDoc()'>Load</button>
  <script>
    function loadDoc(){
      var element = document.querySelector('evo-object_list');
      element.loadDoc();
    }
  </script>
</body>

网络组件

loadDoc: function(){
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("loadInHere").innerHTML = xhttp.responseText;
     }
   }
   xhttp.open("GET", "db.json", true);
   xhttp.send();
 },

JSON

{ 
  "fathers" : [ 
    { 
      "id" : 0,
      "married" : false,
      "name" : "Ronald Taylor",
      "sons" : null,
      "daughters" : [ 
        { 
          "age" : 9,
          "name" : "Barbara"
        }
      ]
    },
  { 
    "id" : 1,
    "married" : false,
    "name" : "Kevin Lopez",
    "sons" : null,
    "daughters" : [ 
      { 
        "age" : 6,
        "name" : "Angela"
        }
      ]
    },
  { 
    "id" : 2,
    "married" : true,
    "name" : "Matthew Harris",
    "sons" : null,
    "daughters" : [ 
      { 
        "age" : 19,
        "name" : "Helen"
        }
      ]
    },
  { 
    "id" : 3,
    "married" : true,
    "name" : "Thomas Lewis",
    "sons" : null,
    "daughters" : [ 
      { 
        "age" : 16,
        "name" : "Michelle"
        },
      { 
        "age" : 8,
        "name" : "Dorothy"
        }
      ]
    },
  { 
    "id" : 4,
    "married" : true,
    "name" : "John Martin",
    "sons" : null,
    "daughters" : [
      ]
    }
  ]
}

etc.....

我的文件可能很长,我不想加载整个文件,是否可以定义文件内的哪些对象以及应返回多少对象。例如,重新单击按钮后,只有前三个父亲,然后是接下来的三个?

我现在只使用 JSON 进行测试,但可能还有其他我现在不知道的文件。

请仅提供纯 JavaScript 答案,我不想使用 jQuery

最佳答案

正如其他人所说,这主要是一个应该在服务器端实现的功能,但为了给您提供一些指导,想法是从 JS 端发送一个参数,例如:

// Note the limit parameter sent to the server
xhttp.open("GET", "db.json?limit=5", true);

// Note the page parameter sent to the server
xhttp.open("GET", "db.json?page=1", true);

// You can even set custom paginations!
xhttp.open("GET", "db.json?page=5&per_page=50", true);

此实现的一个示例是堆栈溢出问题列表,请注意 URL 中的参数

https://stackoverflow.com/questions?page=2&sort=newest

关于javascript - AJAX 仅加载和返回有限数量的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33649649/

相关文章:

javascript - 如何在不重叠的情况下每隔一段时间进行一次 Ajax 调用?

javascript - 在浏览器调整大小之前,Thinglink 图像不可见

php - Laravel 419 未知状态

javascript - 在 javascript/jquery 中构建多部分/表单数据请求

arrays - 使用循环查找特定数组

MySQL group by count(1) 和 having by

Javascript 不向 html 元素添加类

Javascript 切换/开关?

javascript - JS 更新时 iFrame 无法正常显示

mysql - 如何在MySQL中使用group by获取两个不同字段的计数?