Rails 使用 JQuery Ajax 很簡單

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
849   0  
·
2018/07/23
·
3 mins read


我現在很常混合 Rails 與 Javascript Ajax,網頁互動性很好,又可以避開 Turbolinks 的倒退,很簡單好用,有時候,比寫 Link_to 還快,基本上,有兩種最常用的 AJAX:

一,按鈕做一件事

二,執行完後,看結果跳到另一頁

按鈕做一件事很簡單:

不難,就以下幾個步驟:

先把資料寫到 html... 當然你也可以用其他方法,但是這樣很方便,JS 可以直接讀網頁就知道輸入的資料了:

<%= content_tag :div, class: "button_to_AJAX", :data => { rec_id: v1, rec_data: v2, x1: v3 } do %>
  中間看您要放什麼?
<% end -%>

做個按鈕:

$(document).on('turbolinks:load', function() {
  if ($('button_to_AJAX').length > 0) {
    $('button_to_AJAX').off('click').click(function(){
      var rec_id=$(this).data("rec-id");
      var rec_data=$(this).data("rec-data");
      var x1Id=$(this).data("x1");
      $.ajax({
        type: "POST",
        url: "/control/ajxwhatever",
        data: { controller: {rec_id: rec_id, rec_data: rec_data}, x1: x1Id },
        dataType: "script",
        success: function(data) {
          // console.log(data);
        }
      });
    });
  };
});

一個細節,別混用了 data 跟 attr,這兩個看起來一樣,其實完全不同的東西,選一個,就從一而終是我的建議。

router 要設好,最簡單的設定法就是用 resource/collection,get/post/... 就看網頁的屬性了:

resources :control do
  collection do
    post 'ajxwhatever'
  end
end

Controller 接到 Ajax call 後,就玩玩資料,response 設到 JS 回應就好:

 respond_to do |format|
  format.js
end

就這樣,這個 action 對應到 view 的 xx.js.erb 就會被執行了,很簡單,但是有很多細節要注意:

我們用 content_tag 或其他的方式產生 :data => { rec_id: v1, rec_data: v2, x1: v3 },但是在 HTML 上,rec_id 會變成 rec-id,html 不喜歡底線確定!

我們的 response 中的 xx.js.erb 要記住,rails 會先執行 Ruby code,所以寫法要注意,如果你是用

$('<%=".JS-tag-" + id.to_s %>').each(function(){
  $(this).html( "<%= j render(:partial => 'blogs/create', locals: { id: params[:id] }) %>";
);

你等於是每個 .JS-tag-id 都是一樣的內容了,要用

<% Blog.where(id: params[:id]).each do |cc| %>
  $('<%=".JS-tag-" + id.to_s %>').each(function(){
    $(this).html( "<%= j render(:partial => 'blogs/create', locals: { id: params[:id] }) %>";
  );
<% end %>

中間可以改成 $('<%=".JS-tag-" + id.to_s %>').get(0).html(....),但是你如果是用 Javascript,不是 JQuery,那就要小心,中間有一個 DOM 沒找到,你又直接 replace 的話,會死在不知那裡,程式就停在那個找不到的DOM了。

執行完後,看結果跳到另一頁

有時,我們會想要一個AJAX call 到 rails 的 controller action ,再用這個 rails action 來決定下一步,例如:沒錯就到 ok_control_path,有錯就到 wrong_control_path,這樣的的 AJAX 最好用 AJAX html call,沒錯,就是 AJAX 用 html dataType 來執行,使用也很簡單,但是一樣有很多細節:

一定要用 post 

router 一定要設成 post,不然網頁就不會轉了:

resources :control do
  collection do
    post 'ok'
    post 'wrong'
  end
end

control action 就很簡單,跟我們寫其他 rails 一樣,更好的是,redirect_to 的 info 也可以用了,action ok/wrong 或是任何一個 action,基本上就跟寫不是 AJAX call 是一樣的:

respond_to do |format|
  if params[:ok]=="YES"
    format.html { redirect_to ok_control_url(ok: params[:ok]), info: message }
  else
    format.html { redirect_to wrong_control_url(ok: params[:ok]), info: message }
  end
end

要從 JS call 也很簡單,就是一定要要有「 eval () 」來執行了,這也是一個重點:

$.ajax({
  type: "Post",
  url: "/control/ok_or_not",
  dataType: "html",
  data: {
    message: finished_message,
  },
  success: function(data) {
    eval(data);
  }
});

這樣,你就有一個很好用的 AJAX redirect_to 了,好用簡單不囉唆!


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

This article is part of:
分類於:
標籤:
日期:
創作於:2018/07/23,最後更新於:2020/03/14。
合計:784字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.