我尝试在一个新的 Rails 6 项目上成功重现 GoRails 关于无限滚动的教程https://gorails.com/episodes/infinite-scroll-stimulus-js,但无法重现到更新的更旧和更大的项目到 rails 6,包括 webpacker。我用佩吉。目标是滚动图片。但是当我在页面底部时它不起作用,并且不自动加载页面 2,并且我在控制台中收到 406(不可接受)错误
我的 Html 'newsfeed' Pagey 在哪里:
<div data-controller="infinite-scroll">
<div data-infinite-scroll-target="entries">
<%= render "newsfeedpictures" %>
</div>
<div data-infinite-scroll-target="pagination">
<%== pagy_nav(@pagy) %>
</div>
</div>
部分新闻源图片:
<% @pictures.each do |pic| %>
<% if pic.image.attached? %>
<% image_tag(pic.try(:hd_image), :secure => true, class: "img-responsive") %>
<% end %>
<% end %>
控制器:
@pagy, @pictures = pagy(Picture.order(created_at: :desc), items: 5)
respond_to do |format|
format.html
format.json {
render json: { entries: render_to_string(partial: "newsfeedpictures", formats: [:html]), pagination: view_context.pagy_nav(@pagy) }
}
end
无限滚动js,我认为问题出在:
loadMore() {
let next_page = this.paginationTarget.querySelector("a[rel='next']")
if (next_page == null) { return }
let url = next_page.href
console.log("loadmore");
Rails.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: (data) => {
console.log(data)
this.entriesTarget.insertAdjacentHTML('beforeend', data.entries)
this.paginationTarget.innerHTML = data.pagination
}
})
}
我在底部滚动时的服务器响应:
Started GET "/pictures/newsfeed?locale=fr&page=2" for 127.0.0.1 at 2021-06-13 17:27:27 +0200
Processing by PicturesController#newsfeed as GEOJSON
Parameters: {"locale"=>"fr", "page"=>"2"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.2ms) SELECT COUNT(*) FROM "pictures"
Completed 406 Not Acceptable in 5ms (ActiveRecord: 0.4ms | Allocations: 1468)
User excluded error: #<ActionController::UnknownFormat: PicturesController#newsfeed is missing a template for this request format and variant.
request.formats: ["application/json", "text/javascript", "*/*"]
request.variant: []>
ActionController::UnknownFormat (PicturesController#newsfeed is missing a template for this request format and variant.
request.formats: ["application/json", "text/javascript", "*/*"]
request.variant: []):
Chrome 中的控制台:
rails-ujs.js:216 GET http://localhost:3000/pictures/newsfeed?locale=fr&page=2 406 (Not Acceptable)
./node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js.Rails.ajax @ rails-ujs.js:216
loadMore @ infinite_scroll_controller.js:37
(anonymous) @ infinite_scroll_controller.js:26
processIntersectionEntries @ infinite_scroll_controller.js:24
(anonymous) @ infinite_scroll_controller.js:12
rails-ujs.js 第 216 行是
if (xhr.readyState === XMLHttpRequest.OPENED) {
return xhr.send(options.data);
}
json 似乎没问题,因为我在这个 url 上有一些东西:http://localhost:3000/pictures/newsfeed.json?locale=fr 我认为问题出在 Rails.ajax dataType: 'json'