2016-06-20 101 views
0

我想通过AJAX发送选择下拉菜单值控制器如何使用Ajax在Ruby on Rails的

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不chenge后回应值下拉菜单

+0

'数据:{ “城市”:city_js_id}'应该是'数据:{城市:city_js_id}' – Emu

+0

@Emu我更改为{城市:city_js_id},但不工作 –

回答

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; 
    }); 
}); 
+0

我试试这个,但不工作= => **错误{Template is missing} ** –

+0

您可以提供完整路径。让我们说你的部分驻留在'views/panel/_inser.html.erb'里面。是否渲染部分:'panel/insert.html.erb'' – Kumar

+0

看看这个错误,它必须给你找不到的路径。你将能够修复它。 :) – Kumar