2
我正在使用Dart作爲客戶端代碼在我的Rails網站上進行無限滾動。我發現了一個電話的例子,令人驚訝的是,它第一次工作。問題在於它返回的是與我點擊下一個按鈕時所得到的相同的html。我不需要整個頁面,只需要滾動數據。我決定嘗試JSON。該請求由Rails處理,但仍將其呈現爲html。這就是我所做的更改:Rails無法識別JSON作爲響應類型
HTML請求
HttpRequest.request(url).then(onDataLoaded);
JSON請求
HttpRequest.request(url, responseType: 'json').then(onDataLoaded);
變量URL已經從 '下一步' 按鈕的URL的副本:
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爲null。
我在Chrome瀏覽器中檢查了網絡數據,並在響應選項卡上看到完整的html數據。達特代碼必須認爲這是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?在上面的代碼中如何設置格式?
更新
我已經完全重寫的問題。