我正在使用Dart作为客户端代码在我的Rails网站上进行无限滚动。我找到了一个电话的例子,令人惊讶的是,它第一次工作。问题是,如果我点击下一个按钮,它会返回相同的html。我不需要整个页面,只需要滚动数据。我决定尝试使用JSON。该请求由Rails处理,但仍然将其呈现为html。这是我所做的改变:
html请求
HttpRequest.request(url).then(onDataLoaded);
json请求
HttpRequest.request(url, responseType: 'json').then(onDataLoaded);
变量url有一个来自' Next'的网址的副本。按钮:
http://jazzcat.loc/artists?page=2
当我使用此响应处理程序打印到浏览器控制台时:
void onDataLoaded(HttpRequest resp) {
print(resp.statusText);
print(resp.responseHeaders);
print(resp.response);
}
状态文字正常。 响应标头是:
{x-runtime: 0.049101, date: Thu, 09 Jun 2016 23:51:05 GMT, x-content-type-options: nosniff, server: Apache/2.4.18 (Unix) Phusion_Passenger/5.0.24 PHP/5.5.34, x-powered-by: Phusion Passenger 5.0.24, x-frame-options: SAMEORIGIN, content-type: text/html; charset=utf-8, status: 200 OK, cache-control: max-age=0, private, must-revalidate, transfer-encoding: chunked, etag: W/"fb290bd42f831f80ea9359040304ea39", connection: Keep-Alive, keep-alive: timeout=5, max=100, x-xss-protection: 1; mode=block, x-request-id: 9921c6c7-2fb6-43b9-89d3-636fb4a3aec0}
rest.response为空。
我在Chrome浏览器中检查了网络数据,并在响应标签上看到了完整的html数据。 Dart代码必须认为它是json并且无法显示它
这是来自json响应类型请求的Rails应用程序日志:
Started GET "/artists?page=2" for 127.0.0.1 at 2016-06-10 17:05:06 -0700
Processing by ArtistsController#index as */*
Parameters: {"page"=>"2"}
ArtistsController index method
Rendered artists/_list_subnav.html.erb (0.2ms)
Artist Load (1.3ms) SELECT `artists`.* FROM `artists` ORDER BY last_name, first_name LIMIT 25 OFFSET 25
(0.4ms) SELECT COUNT(*) FROM `artists`
Rendered artists/index.html.erb within layouts/application (22.9ms)
Completed 200 OK in 31ms (Views: 28.6ms | ActiveRecord: 1.7ms)
我有一个index.json.erb,我也尝试将其添加到控制器:
def index
# Perform any filtering using ransack search
logger.debug "ArtistsController index method format"
@q = Artist.search(params[:q])
# Partition the output using kaminari page
@artists = @q.result.order('last_name', 'first_name').page(params[:page])
respond_to do |format|
format.html
format.json { render :json => @artists }
end
end
如何让Rails渲染json?如何在上面的代码中设置格式?
更新
我完全重写了这个问题。
答案 0 :(得分:3)
花了两天的时间才找到它。您需要为请求添加Accept标头。以下是我解决上述问题的方法:
Map headers = {'Accept': 'application/json'};
HttpRequest.request(url, requestHeaders: headers).then(onDataLoaded);