2011-04-04 89 views
0

我有一个应用程序,我想在后端做一些计算,然后通过Ajax在前端显示结果。我没有使用ActiveRecord。如何在Rails 3中使用js.erb模板和Ajax?

我显示了JavaScript代码而不是执行它。 Webrick在按下转换按钮后说:

Started POST "/site/convert.js" for <ip address> at 2011-04-05 01:37:09 +0300 
    Processing by SiteController#convert as JS 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"K9De9/J5bsnOxqLdmvl02sOVgmU3c4gEZ/n7DBwJdrw=", "radix"=>"10", "number"=>"2", "commit"=>"Convert"} 
Rendered site/convert.js.erb (0.5ms) 
Completed 200 OK in 28ms (Views: 22.9ms) 

为什么JavaScript代码没有执行?

site_controller.rb:

class SiteController < ApplicationController 
    def index 
    end 

    def convert 
    number = params[:number] 
    from = params[:radix] 
    @decimal = Converter::convert(number, from.to_i, 10) 
    @hexadecimal = Converter::convert(number, from.to_i, 16) 
    @binary = Converter::convert(number, from.to_i, 2) 
    end 

end 

网站/ index.html.erb:

<%= form_tag site_convert_path(:format => :js), :id => 'conversion', :remote => true do %> 
    <%= radio_button_tag 'radix', 10, true %> Decimal 
    <%= radio_button_tag 'radix', 16 %> Hexadecimal 
    <%= radio_button_tag 'radix', 2 %> Binary 
    <%= number_field_tag 'number', '', :size => '20', :min => 0 %> 
    <%= submit_tag 'Convert' %> 
<% end %> 

<button id="convert" type="button">Convert</button> 

<table> 
    <thead>Conversions</thead> 
    <tr> 
    <th>Decimal</th> 
    <th>Hexadecimal</th> 
    <th>Binary</th> 
    </tr> 
    <tr> 
    <td id="decimal_converted"></td> 
    <td id="hexadecimal_converted"></td> 
    <td id="binary_converted"></td> 
    </tr> 

</table> 

网站/ convert.js.erb:

$('#decimal_converted').text("<%= @decimal %>"); 
$('#hexadecimal_converted').text("<%= @hexadecimal %>"); 
$('#binary_converted').text("<%= @binary %>"); 

的routes.rb:

Conversions::Application.routes.draw do 
    root :to => 'site#index' 
    post 'site/convert' 
end 

回答

2

问题已解决。有使用Rails jQuery的适配器,即rails.js,jQuery的装载之前,所以在之后的布局变化的问题解决了该问题:

<%= javascript_include_tag ['rails', 'jquery'] %> 

改为:

<%= javascript_include_tag ['jquery', 'rails'] %> 
相关问题