2016-05-29 37 views
0

在Rails中使用ajax的這個例子http://www.kunce.net/2013/10/ror-dynamic-dropdown-box-with-ajax/ 我有它不起作用,我做錯了什麼? 罐頭必須連接寶石或是它不工作的ustanevshy方法? 我需要找到用戶在select中選擇的divas數據而無需刷新頁面。 檢視:在rails中使用ajax

<div id="select_div"> 
    <select name="city_id" id="city_id"> 
     <option value="0">Lisbon</option> 
     <option value="1">Madrid</option> 
     <option value="2">Prague</option> 
    </select> 
</div> 
<div id="result_div"> 
    <h4>Lisbon is selected</h4> 
</div> 

<script> 
    $(document).ready(function() { 
    $('#city_id').change(function() { 
     $.ajax({ 
      url: "<%= update_text_path %>", 
      data: { 
       city_name: $("#city_id option:selected").text() 
      }, 
      dataType: "script" 
     }); 
    }); 
    }); 
</script> 

routes.rb中:

get "static_pages/update_text", as: "update_text" 

控制器static_pages:

def update_text 
    @city_text = params[:city_name] 
end 

視圖/ static_pages/update_text.js.erb

$('#result_div').html("<h4>You have changed the city to: <%= @city_text %></h4>"); 
+0

「不起作用」是什麼意思?你的瀏覽器有什麼變化嗎?你的服務器日誌顯示了什麼? –

+0

Lanny Bose,在瀏覽器中的更改不是 終端寫入: [2016-05-30 00:24:37] ERROR bad URI'/%3C%=%20city_id%20 %% 3E?city_id = 2&_ = 1464557016658 」。 –

+0

嘗試移除「<%= update_text_path%>」附近的引號。它可能是雙引號的嗎? –

回答

0

字面值<%= update_text_path %>似乎被用作URL。檢查您的文件是否被命名爲app/views/static_pages/home.html.erb,而不是app/views/static_pages/home.html。只有.erb文件可以使用ERB標記。

+0

我使用app/views/static_pages/home.html.erb –