Rails Ajax 筆記

ujs使用

安裝

Gemfile 中已經(jīng)使用了 gem 'jquery-rails'
在 application.js 中增加這兩行:

//= require jquery
//= require jquery_ujs

案例:
<%= link_to "刪除", product, :method => :delete, :data => { :confirm => "點(diǎn)擊確定繼續(xù)" } %>

  1. 使用了 :data => { :confirm => "點(diǎn)擊確定繼續(xù)" }這個屬性,為我們添加了 data-confirm="點(diǎn)擊確定繼續(xù)" 這樣的 HTML 代碼,之后 ujs 將它處理成一個彈出框。
  2. :method => :delete屬性,這為我們的連接上增加了 data-method="delete" 屬性,這樣,ujs 會把這個點(diǎn)擊動作,會發(fā)送一個 delete 請求刪除資源,這是符合 REST 要求的。
  3. <%= f.submit nil, :data => { :"disable-with" => "請稍等..." } %>
    給 a 標(biāo)簽增加 data-disable-with 屬性,當(dāng)點(diǎn)擊它的時候,使它禁用,并提示文字信息。這樣可以防止用戶多次提交表單,或者重復(fù)的鏈接操作。
def create
  sleep 10
  @product = Product.new(product_params)

無刷新頁面操作

產(chǎn)生一個 ajax 的請求,我們在表單上增加一個參數(shù) remote: true在表單裡加入remote,這樣ujs就會知道要發(fā)非同步請求.
<%= form_for @todo, { remote: true } do |f| %>

這時,ujs 將會調(diào)用 jQuery.ajax() 提交表單,此時的請求是一個 text/javascript 請求,Rails 會返回給我們相應(yīng)的結(jié)果,在我們的 action 里,增加這樣的聲明:在保存(save)成功時,我們返回給視圖(view)一個 js 片段

controller

respond_to do |format|
  if @product.save
    format.html {...}
    format.js
  else
    format.html {...}
    format.js
  end
end

新增create.js.erb
創(chuàng)建一個新文件 app/views/products/create.js.erb,在這里,我們將新添加商品,顯示在上面的列表中。

$('#productsTable').prepend('<%= j render(@product) %>');
$('#productFormModal').modal('hide');

escape_javascript j render 來的link 處理雙引號問題。

app/views/products/_product.html.erb

<tr id="product_<%= product.id %>">
  <td id="product_<%= product.id %>_name"><%= link_to product.name, product %></td>
  <td id="product_<%= product.id %>_price" class="text-right"><%= number_to_currency product.price, unit: "¥" %></td>
  <td>
    <%= link_to t('.edit', :default => t("helpers.links.edit")), edit_product_path(product), :class => 'btn btn-default btn-xs editProductLink', remote: true, data: { type: 'json' } %>
    <%= link_to t('.destroy',
      :default => t("helpers.links.destroy")), product,
      :remote => true,
      :method => :delete,
      :data => { :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')) },
      :class => 'btn btn-xs btn-danger' %>
  </td>
</tr>

json 數(shù)據(jù)的頁面處理

<%= link_to t('.edit', :default => t("helpers.links.edit")), edit_product_path(product), remote: true, data: { type: 'json' }, :class => 'btn btn-primary btn-xs editProductLink' %>

增加remote: true, data: { type: 'json' } 和class .editProductLink

新建一個文件,app/assets/javascripts/products.coffee

jQuery ->
  $(".editProductLink")
    .on "ajax:success", (e, data, status, xhr) ->
      $('#alert-content').hide() [1]
      $('#editProductFormModal').modal('show') [2]
      $('#editProductName').val(data['name']) [3]
      $('#editProductDescription').val(data['description']) [3]
      $('#editProductPrice').val(data['price']) [3]
      $("#editProductForm").attr('action', '/products/'+data['id']) [4]

[3] 填入編輯的信息
[4] 更改表單提交的地址

controller

def edit
  respond_to do |format
    format.html
    format.json { render json: @product, status: :ok, location: @product } [1]
  end
end

[1] 讓 edit 方法,返回給我們商品的 json 格式信息。

def update
  respond_to do |format|
    if @product.update(product_params)
      format.html { redirect_to @product, notice: 'Product was successfully updated.' }
      format.json [1]
    else
      format.html { render :edit }
      format.json { render json: @product.errors.full_messages.join(', '), status: :error } [2]
    end
  end
end

[1] 我們讓 update 方法,可以接受 json 的請求,
[2] 當(dāng) update 失敗時,我們需要把失敗的原因告訴客戶端,它也是 json 格式的。

  $("#editProductForm")
    .on "ajax:success", (e, data, status, xhr) ->
      $('#editProductFormModal').modal('hide')
      $('#product_'+data['id']+'_name').html(  data['name'] )
      $('#product_'+data['id']+'_price').html(  data['price'] )
    .on "ajax:error", (e, xhr, status, error) ->
      $('#alert-content').show()
      $('#alert-content #msg').html( xhr.responseText )

案例

<%= f.collection_select :district, District.all, :id, :title, {prompt: '區(qū)'}, { class: 'custom-select', 'data-remote' => true, 'data-type' => 'script', 'data-url' => url_for(controller: 'settings', action: 'fetch_district_detail', format: 'js') } %>
"script": 返回純文本 JavaScript 代碼。不會自動緩存結(jié)果。除非設(shè)置了 "cache" 參數(shù)。注意:在遠(yuǎn)程請求時(不在同一個域下),所有 POST 請求都將轉(zhuǎn)為 GET 請求。(因?yàn)閷⑹褂?DOM 的 script標(biāo)簽來加載)
http://www.w3school.com.cn/jquery/ajax_ajax.asp

controller

def show
  @subdistrict = {}
end
def fetch_district_detail
  @subdistrict = Subdistrict.where(district_id: params[:instructor][:district])
end

fetch_district_detail.js.erb

$("#sub-district").html("<%= j select_tag :street, options_from_collection_for_select(@subdistrict, :id, :subtitle), { class: 'custom-select', id: 'sub-district' } %>");

最基本的jquery ajax寫法包含

url:發(fā)送非同步請求的對象,也就是索求資料的 server 的網(wǎng)址
method:發(fā)送請求的類型,如 GET、POST、DELETE、PATCH 等
data:要附帶在請求裡發(fā)送給 server 的資料
dataType:要求 server 回傳的資料格式
success:成功後要執(zhí)行的 function,function 會帶入 server 回傳的資料

未完成

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容