我在ROR中創建儀表板。我有一個組合框,onchange將ajax發送到儀表板以相應地獲取數據。基於我選擇的價值,我將獲得數據,並且我將相應地在高圖中呈現這些值。如何將對象從控制器返回到rails中的ajax
hbar.html.erb
<select name="hBarParam" id="hBarParam" class="hBarParam">
<option value="Nothing"></option>
<option value="Today" class="selected">Today</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<div id="postsHBar" style="width:100%; height:500px" class="postsHBar"></div>
$(".hBarParam").change(function(){
var str = $("#hBarParam option:selected").text();
$.get("/dashboard/hbar?hBarParam="+str,function(data){
alert(<%= @postsHBarClean.map{|p|p[1] } %>)
}).done(function() {
alert(<%= @postsHBarClean.map{|p|p[1] } %>)
//render new highcharts with different like postsHBarClean, postsHBarSalvage,etc
$(function() {
new Highcharts.Chart({
chart: {
type: 'bar',
renderTo: 'postsHBar',
backgroundColor:null
},
title: {
text:...
},
xAxis: {
categories: <%= raw @postsHBar.map{|p| p.make_vehicle}.map(&:to_s) %>,
},
yAxis: {
min: 0,
title: {
text: 'Count (Thousands)',
align: 'high'
}...
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
....
},
credits: {
enabled: false
},
series: [{
name: "Clean",
data: <%= @postsHBarClean.map{|p|p[1] } %>
},
{
name: "Salvage",
data: <%= @postsHBarSalvage.map{|p|p[1] } %>
}.....]
});
});
});
});
控制器代碼
class DashboardController < ApplicationController
respond_to :html, :js, :json
# GET /dashboard/hbar
def hbar
puts params["hBarParam"]
if params["hBarParam"] == "Today"
postsHBarParam = "created_day = 26"
elsif params["hBarParam"] == "Monthly"
postsHBarParam = "created_month = 'April'"
else
postsHBarParam = "created_day between 22 and 27"
end
puts postsHBarParam
# postsHBarParam = "created_day = 26"
@postsHBarClean = Post.where(postsHBarParam + " and title_status like ? and make_vehicle is not null", "clean").group(:make_vehicle).count.to_a
@postsHBarSalvage = Post.where(postsHBarParam +" and title_status like ? and make_vehicle is not null", "salvage").group(:make_vehicle).count.to_a
@postsHBarPartsOnly = Post.where(postsHBarParam +" and title_status like ? and make_vehicle is not null", "parts only").group(:make_vehicle).count.to_a
@postsHBarRebuilt = Post.where(postsHBarParam +" and title_status like ? and make_vehicle is not null", "rebuilt").group(:make_vehicle).count.to_a
@postsHBarLien = Post.where(postsHBarParam +" and title_status like ? and make_vehicle is not null", "lien").group(:make_vehicle).count.to_a
@postsHBar = Post.select(:make_vehicle).where(postsHBarParam +" and title_status is not null and make_vehicle is not null").uniq
puts @postsHBarClean
respond_to do |format|
format.js
format.html
end
end
的問題是,圖表呈現..但使用默認值(即控制其他部分),所以每當我改變選擇選項...「把字符串」作品但圖表採用相同的值,即頁面加載期間的值。 沒有語法錯誤或括號丟失:P
我在這個問題上陷入困境,不知道如何解決它。 :(
您需要使用'hbar.js.erb'來響應作爲'JS'的'hbar'動作(而不是'HTML') – MrYoshiji
按照建議創建hbar.js.erb並編寫代碼來呈現圖表在js.erb文件中有新的值 –
您應該將所有hbar.html.erb代碼放在一個局部_hbar.html.erb中,使控制器的局部部分相同 – Thorin