JQueryと私のRailsの練習では、 'form_tag'から2つのパラメータを取得し、コントローラの計算結果をビュー 'ネットワークビュー(Chromeデベロッパーツール)の結果が表示されますが、何も表示されません。 ルート:Rails 5はJQueryの結果をレンダリングしていません
get '/calculator', to: 'users#bmi_calc'
users_controller.rb:
def bmi_calc
bmi_table = {
"Very severely underweight" => { from: 0.0, to: 15.0 },
"Severely underweight" => { from: 15.1, to: 16.0 },
"Underweight" => { from: 16.1, to: 18.5 },
"Normal (healthy weight)" => { from: 18.51, to: 25.0 },
"Overweight" => { from: 25.1, to: 30.0 },
"Obese class I (moderately obese)" => { from: 30.1, to: 35.0 },
"Obese class II (severely obese)" => { from: 35.1, to: 40.0 },
"Obese class III (very severely obese)" => { from: 40.1, to: 60.0 },
"Pure fat factor" => { from: 60.1, to: 100.0}
}
weight = params[:mass].to_f
height = params[:height].to_f
if weight > 0 && height > 0
resultado = ''
@bmi = weight/height ** 2
bmi_table.each do |advice, range|
if (@bmi > range[:from]) && (@bmi < range[:to])
resultado = advice
end
end
respond_to do |format|
format.json { render json: {resultado: resultado} }
end
else
redirect_to current_user
end
end
users.js.erb:
$(document).ready(function(){
$("#calculator-img").click(function(){
$.getJSON('/calculator', function(data) {
var res = data.resultado;
$("#bmi-result").html(res);
});
});
});
ユーザ/ show.html.erb:
ここで関連のコードであります<div class="row">
<aside class="col-md-4">
<section class="user_info">
<h1><%= @user.name %></h1>
</section>
<section class="bmi_form">
<%= render 'bmi_form' %>
</section>
<div id="bmi-result">
</div>
</aside>
<div class="col-md-6">
<section class="mid_section">
<p>Some text</p>
<h2>BMI standard table</h2>
<%= image_tag "BMItable.png", alt: "BMI stardard table" %>
</section>
</div>
</div>
_bmi_form.html.erb:
<%= form_tag calculator_path, method: "get", remote: true, class: "navbar-left" do %>
<%= label_tag :mass, "Your mass (weight) in Kg" %>
<%= number_field_tag :mass, params[:mass], step: 0.01, class: "form-control" %>
<%= label_tag :height, "Your height in meters" %>
<%= number_field_tag :height, params[:height], step: 0.01, class: "form-control" %>
<%= image_submit_tag("BMI.gif", id: "calculator-img") %>
<% end %>
そして最後に、これは私がクロームの開発者ツールで得るものです:
pleseは私は私が間違っているのか理解に役立ちます。おかげ (これは私が解決しようと挑戦です:私は配信終了にhttps://gist.github.com/JonaMX/d29a754ae625664b0cf7 は私はないかなりまったく...結果で新しいページをレンダリングする必要がありました)
JavaScriptが実行されているかどうか最初に確認します。 'console.log(" Something ");や' alert( "Something") 'を設定してください。フォームを 'remote:true'に設定しました。つまり、* onclick *イベントだけでなく、* submit *を押すだけでajaxリクエストも実行されます。これはリクエストヘッダーにも表示されます。 'Accept = application/json'がJSON要求によって行われている場合よりも。 Railsが 'remote:true'イベントでそれを処理すると、' Accept = application/javascript'を要求していると思いますが、それについて私を引用しません。 –