简体   繁体   English

如何在AJAX响应中发出无限滚动的结束信号?

[英]How to signal end of infinite scroll in AJAX response?

I have a site which I built an infinite scroll for and as you scroll it loads the next X results, but I was wondering if theres a standard or better / prefered way of signaling you have come to the end and not to do any more requests. 我有一个网站,我建立了一个无限滚动,当你滚动它加载下一个X结果,但我想知道是否有一个标准的或更好的/首选的信号方式你已经走到尽头而不再做任何请求。

At the moment it justs 404s when requesting data thats after the "end" of the data. 目前,在数据“结束”之后请求数据时,它只有404秒。 If AJAX call receives an error/the 404 in response then it will remember not to make a call anymore. 如果AJAX调用收到错误/ 404响应,那么它将记住不再打电话。

But to me it feels a bit raw and was wondering whats the usual (if any) way of dealing with this is. 但对我来说,它感觉有点原始,并想知道通常(如果有的话)解决这个问题的方式是什么。

How are you handling paging? 你是如何处理分页的? Often it is recommended to include a "next page" link in your AJAX response. 通常建议在AJAX响应中包含“下一页”链接。 If you do so it avoids having to do math on the client, and provides an easy communication mechanism, just don't include the link if it would not be valid. 如果这样做,它可以避免在客户端上进行数学运算,并提供简单的通信机制,如果链接无效则不要包含链接。

If you Ajax is returning HTML or text, then just return an empty response to signify that there is no more data. 如果Ajax返回HTML或文本,则只返回一个空响应,表示没有更多数据。

If the Ajax is returning JSON, then you can just add "status" property to the object representation. 如果Ajax返回JSON,那么您只需将“status”属性添加到对象表示中即可。

Either way you should probably respond with HTTP 200, not 404. 无论哪种方式,你应该回应HTTP 200,而不是404。

If we assume that your "get results" API call looks something like this: 如果我们假设您的“获得结果”API调用看起来像这样:

$.get('/results', { start: n }, function() ...); // for ex, /results?start=0

And returns something like: 并返回如下内容:

[{ name: 'Result 1' }, { name: 'Result 2' }, ... ]

Where n is the number of results already loaded, then it doesn't really make sense semantically to return a 404 error, which means the requested resource (which is /results ) does not exist. 其中n是已经加载的结果数,那么返回404错误在语义上并没有意义,这意味着所请求的资源/results )不存在。 This is not true; 这不是真的; /results does exist, but the request parameters result in no data. /results 确实存在,但请求参数不会导致数据。

It is more appropriate to return a 200 with an empty array, 返回带有空数组的200更合适

[]

...or respond with HTTP 204 No Content, which means that the request was successful, but there is nothing to return. ...或者使用HTTP 204 No Content回复,这意味着请求成功,但没有任何回复。 This does save a few bytes since the server needn't send Content-Type or Content-Length headers and a response body. 这确实节省了几个字节,因为服务器不需要发送Content-TypeContent-Length头和响应主体。

(I'd use the 204.) (我用的是204.)

Either way, your client-side script knows that a 204 or an array of length 0 means that there's no more data, and can stop making requests. 无论哪种方式,您的客户端脚本都知道204或长度为0的数组意味着没有更多数据,并且可以停止发出请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM