如何在 rails 上的 ruby 中使用 Ajax

How to Use Ajax in ruby on rails

我想通过 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'

views/panel/insert.html.erb

<%= @city_ids %>

but @city_ids dont respond value after chenge drop down menu

您需要通过 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;
  });
});