我想我做了一個亂七八糟的JQuery和我的Rails練習,我打算從'form_tag'獲取兩個參數,然後在我的控制器中在視圖中的''中渲染計算結果,我在「網絡」視圖(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 %>
最後,這是我在Chrome開發者工具得到:
普萊舍幫助我理解我在做什麼錯。感謝 (這是我要解決的挑戰:https://gist.github.com/JonaMX/d29a754ae625664b0cf7 在我提供的結束,但我不得不呈現一個新的頁面,結果...不漂亮的話)
首先檢查您的JavaScript是否運行。設置一個'console.log(「Something」);'或'alert(「Something」)''。你已經將表單設置爲'remote:true',這意味着ajax請求也可以通過按* submit *來完成,而不僅僅是* onclick *事件。這在請求頭中也是可見的。如果'Accept = application/json'比它通過你的JSON請求完成。如果Rails使用'remote:true'事件處理它,我相信它正在請求'Accept = application/javascript',但不要引用我的話。 –