如何在rails上的ruby中使用Ajax

时间:2016-06-20 10:56:01

标签: ruby-on-rails ruby ajax ruby-on-rails-3

我想通过ajax

将选定的下拉菜单值发送到控制器

panel_controller.rb

class PanelController < ApplicationController

      def insert
         @city_ids = params[:city]
      end
end

panel.js.erb

$(document).ready(function() {
    $('#f_city_id').change(function() {
        var city_js_id = this.value
        $.ajax({
            url: '/panel/insert',
            type: 'GET',
            data: {"city": city_js_id},
            success: function (data,status)
            {
                alert(this.url);
            }
        });
        return false;
    });
});

的routes.rb

get '/panel/insert' => 'panel#insert'

视图/板/ insert.html.erb

<%= @city_ids %>
  

@city_ids 在变换下拉菜单后不响应值

1 个答案:

答案 0 :(得分:1)

您需要使用insert方法回复。

尝试这样做

class PanelController < ApplicationController
  def insert
    @city_ids = params[:city]
    respond_to do |format|
      format.html { render partial: 'insert.html.erb' }
    end
  end
end

使用新内容_insert.html.erb

创建部分文件
<%= @city_ids %>

在你的panel.js.erb中尝试捕获响应,并在必要时将其附加到DOM中。您的更新值将显示在页面上。

$(document).ready(function() {
  $('#f_city_id').change(function() {
    var city_js_id = this.value
    $.ajax({
        url: '/panel/insert',
        type: 'GET',
        data: {"city": city_js_id},
        success: function (res){
            $("#somediv").html(res);
            //You will get the partial's content with the new data and you'll only need to append it to your page.
        }
    });
    return false;
  });
});