Send & process .json request (in Rails app)

时间:2015-06-26 09:53:01

标签: javascript ruby-on-rails ajax json

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:

  1. How to create this request (generate it from simple form_for).
  2. How to calculate area(I mean where:)) and give response.

Sorry for lack of code and information. I will be very glad for quick and simple answer.

1 个答案:

答案 0 :(得分:0)

只是关于使用ajax需要做什么的小摘要: -

  1. 创建模型 areamigrate表,并在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%>

  2. routes.rb 中添加路线,以便在使用ajax提交后处理发布表单

    match '/find_area', :to => 'areas#find_area'

  3. 控制器方法中
  4. ,从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

  5. 渲染 js.erb 以显示有关该区域的弹出/文本以及使用css隐藏表单

    在find_area.js.erb里面

    ##using any hidden div already present on the page $("#show_area").html("The area is <%= @area%>").show();