2012-01-08 83 views
1

林軌3.1,我創建使用Ajax搜索表單,我已經用POST方法的工作形式,我缺少的東西在這裏... 所以,在我看來,我有的Ajax查詢和Ruby on Rails

<%= form_tag(root_path, :method => "post",:id =>"formid") do %> 
    <%= label_tag(:number1, "El que quiero") %> 
    <%= text_field_tag :quiero, nil, :class => 'drug_autocomplete' %> 
    <%= hidden_field_tag :number1 %> 

    <%= label_tag(:number1, "El modelo que tengo") %> 
    <%= text_field_tag :tengo, nil, :class => 'drug_autocomplete' %> 
    <%= hidden_field_tag :number2 %> 

    <%= label_tag(:size1, "Talla de el que tengo") %> 
    <%= text_field_tag :size1%> 

    <%= submit_tag("Do it!") %> 

<% end %> 

好吧,我在application.js中寫了一些東西來處理提交事件。

jQuery.ajaxSetup({ 
    'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
}) 

jQuery.fn.submitWithAjax = function() { 
    this.submit(function() { 
    $.post(this.action, $(this).serialize(), null, "script"); 
    return false; 
    }) 
    return this; 
}; 

$(document).ready(function() { 
    $("#form_id").submitWithAjax(); 
}) 

控制器會重新設置表單中的參數,並像這樣創建對數據庫的查詢。

@itemsok = Contribution.where("first_item_id = ?",item1.id).where("second_item_id = ?",item2.id).where("second_item_grade = ?",size1 

,然後返回在數據庫中找到同一視圖

<%if not @itemsok.nil? 
    @itemsok.each do |searches| 
%> 
<table> 
<tr> 
    <td style="width:100px;"><%= searches.first_item.description %> </td> 
    <td style="width:150px; font-size:30px;"><%= searches.first_item_grade %> </td> 


    <td style="width:150px;"><%= searches.second_item.description %> </td> 
    <td style="width:150px; font-size:30px;"><%= searches.second_item_grade %> </td> 
    <td style="width:150px; font-size:18px;"><a href="<%= contribution_path(searches.id) %>">Show</a> </td> 


</tr> 
</table> 

的參數我想實現的是相同的頁面創建一個查詢到數據庫,但與阿賈克斯所以沒有重裝是必要的。 第一個問題,我必須從JavaScript中的某處處理表單中的數據,在哪裏? 第二個問題,就是當回

我完全在Ajax和Rails的丟失,所以任何幫助/提示將非常讚賞我怎麼處理數據。 在此先感謝。 對不起,我的英文很糟糕。

回答

2

您對submitWithAjax功能調用序列化()的準備表單數據爲您服務。

您的表單操作控制器需要響應format.js ABOVE format.html,並且您需要一個與「.js.erb」擴展名相應的視圖文件夾中的操作名稱匹配的文件。

在這一「.js.erb」文件,你可以調用任意jQuery來代替內容,改變頁面的元素,或觸發動作。其他

$('#lightBoxClose').trigger('click'); 
$('#flashContentContainer').html('<%= escape_javascript(render :partial => "shared/flash_bar") %></div>'); 

的一件事是,以確保您的應用程序與format.js行動響應你可以改變你submitWithAjax功能,像這樣:

jQuery.fn.submitWithAjax = function() { 
    this.submit(function() { 
    $.post(this.action + '.js', $(this).serialize(), null, "script"); 
    return false; 
    }) 
    return this; 
}; 

注意」的.js'。

如果你還沒有看到它退房this railscast

0

這是最簡單的使用Rails本地AJAX工具來處理這個問題。換句話說,你的表單標籤應該是這樣的(注意remote PARAM):

form_tag(root_path, :method => "post",:id =>"formid", :remote => true) 

這是所有你需要通過AJAX發佈。但是,你需要處理這個迴應。在JavaScript文件中,這樣做:

$('#formid') 
    .bind('ajax:success', function(response) { 
     // response is what gets sent from the controller 
     // so send only the dynamic data and insert it into the DOM 
    } 

看到其他AJAX回調像ajax:completeajax:error等了Rails 3.1的文檔。