簡體   English   中英

在Ruby on Rails中使用Javascript

[英]Using Javascript in Ruby on Rails

我有一個下拉列表,您可以在其中選擇一個人。

<%= select_tag "person", options_from_collection_for_select(Person.all, :id, :name, 1) %>

選擇一個人后,我要顯示該人的電話號碼。 我怎樣才能做到這一點?

看了很多有關如何在RoR中使用Javascript / jQuery / CoffeeScript的解決方案后,我對在文件中放置什么以及使用什么感到有些困惑。 有人可以給我一個簡單的例子嗎?

在onchange事件中將您的已更改人員ID傳遞給javascript函數。


<%= select_tag "person", options_from_collection_for_select(Person.all, :id, :name, 1) ,
 :onchange => "your_js_function_to_display_phone_for(this.value)"%>

觸發Ajax請求並從數據庫返回電話號碼。 (如果人員列表很小,您也可以從客戶端執行此操作)


<script type="text/javascript">

function your_js_function_to_display_phone_for(person_id)
{

// Given a person_id 
// I am assuming this route will return me the Phone Number 

new Ajax.Request('/person/get_phone_number/'+person_id,
{asynchronous:true, evalScripts:true,
method:'post', 
onSuccess:function(request)
{
    // Modify this place to whether update on particular div_id 
    // or do appropriate action with returned request.body 

    alert("Phone Number for this Person is: "+request.body);
}, 
parameters:Form.serialize(this)});
}

</script>

編輯:

您的控制器應執行以下操作。

class PersonController
    def get_phone_number
        person = Person.find(params[:id])
        phone_number = person.get_phone_number 
        render :text => phone_number 
    end 
end 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM