I have a simple task. User should be able to enter width and height in a form and after click the form should generate request(link) like following:
/find_area.json?width[]=:width&height[]=:height
App should generate response (area = height * width) and display it dynamically on a page.
All user actions have be saved, so it should be POST request.
My questions are:
Sorry for lack of code and information. I will be very glad for quick and simple answer.
答案 0 :(得分:0)
只是关于使用ajax需要做什么的小摘要: -
创建模型 area
和migrate
表,并在form_for
rails g model Area height:integer width:integer
run rake db:migrate
//view part
<%= form_for(@area,:url=>"areas/find_area",:remote=>true) do |f |%>
<%= f.text_field :width ,:placeholder=>"Enter width",:required=>"true"%>
<%= f.text_field :height ,:placeholder=>"Enter height",:required=>"true"%>
<button type="submit" data-remote="true"> Calculate Area</button>
<%end%>
在 routes.rb 中添加路线,以便在使用ajax提交后处理发布表单
match '/find_area', :to => 'areas#find_area'
,从params获取值并计算区域
//inside areas_controller.rb,
def find_area
width,height=params[:width],params[:height]
@area=width*height
respond_to do |format|
if @area
format.js
else
format.js { render :json => @area.errors.full_messages.join(' '), :status => 400 }
end
end
end
渲染 js.erb 以显示有关该区域的弹出/文本以及使用css隐藏表单
在find_area.js.erb里面
##using any hidden div already present on the page
$("#show_area").html("The area is <%= @area%>").show();