ujs使用
安裝
Gemfile 中已經(jīng)使用了 gem 'jquery-rails'
在 application.js 中增加這兩行:
//= require jquery
//= require jquery_ujs
案例:
<%= link_to "刪除", product, :method => :delete, :data => { :confirm => "點(diǎn)擊確定繼續(xù)" } %>
- 使用了
:data => { :confirm => "點(diǎn)擊確定繼續(xù)" }
這個(gè)屬性,為我們添加了 data-confirm="點(diǎn)擊確定繼續(xù)" 這樣的 HTML 代碼,之后 ujs 將它處理成一個(gè)彈出框扰魂。 -
:method => :delete
屬性帽馋,這為我們的連接上增加了 data-method="delete" 屬性,這樣好爬,ujs 會(huì)把這個(gè)點(diǎn)擊動(dòng)作,會(huì)發(fā)送一個(gè) delete 請(qǐng)求刪除資源,這是符合 REST 要求的烤低。 -
<%= f.submit nil, :data => { :"disable-with" => "請(qǐng)稍等..." } %>
給 a 標(biāo)簽增加 data-disable-with 屬性,當(dāng)點(diǎn)擊它的時(shí)候笆载,使它禁用扑馁,并提示文字信息。這樣可以防止用戶多次提交表單凉驻,或者重復(fù)的鏈接操作腻要。
def create
sleep 10
@product = Product.new(product_params)
無刷新頁面操作
產(chǎn)生一個(gè) ajax 的請(qǐng)求,我們?cè)诒韱紊显黾右粋€(gè)參數(shù) remote: true
在表單裡加入remote涝登,這樣ujs就會(huì)知道要發(fā)非同步請(qǐng)求.
<%= form_for @todo, { remote: true } do |f| %>
這時(shí)雄家,ujs 將會(huì)調(diào)用 jQuery.ajax() 提交表單,此時(shí)的請(qǐng)求是一個(gè) text/javascript 請(qǐng)求胀滚,Rails 會(huì)返回給我們相應(yīng)的結(jié)果趟济,在我們的 action 里,增加這樣的聲明:在保存(save)成功時(shí)咽笼,我們返回給視圖(view)一個(gè) 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)建一個(gè)新文件 app/views/products/create.js.erb顷编,在這里,我們將新添加商品褐荷,顯示在上面的列表中勾效。
$('#productsTable').prepend('<%= j render(@product) %>');
$('#productFormModal').modal('hide');
escape_javascript
j
render 來的link 處理雙引號(hào)問題。
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
新建一個(gè)文件叛甫,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 的請(qǐng)求萌腿,
[2] 當(dāng) update 失敗時(shí),我們需要把失敗的原因告訴客戶端毁菱,它也是 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 代碼。不會(huì)自動(dòng)緩存結(jié)果贮庞。除非設(shè)置了 "cache" 參數(shù)峦筒。注意:在遠(yuǎn)程請(qǐng)求時(shí)(不在同一個(gè)域下),所有 POST 請(qǐng)求都將轉(zhuǎn)為 GET 請(qǐng)求窗慎。(因?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ā)送非同步請(qǐng)求的對(duì)象物喷,也就是索求資料的 server 的網(wǎng)址
method:發(fā)送請(qǐng)求的類型,如 GET遮斥、POST峦失、DELETE、PATCH 等
data:要附帶在請(qǐng)求裡發(fā)送給 server 的資料
dataType:要求 server 回傳的資料格式
success:成功後要執(zhí)行的 function术吗,function 會(huì)帶入 server 回傳的資料