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ù)" }這個(gè)屬性,為我們添加了 data-confirm="點(diǎn)擊確定繼續(xù)" 這樣的 HTML 代碼,之后 ujs 將它處理成一個(gè)彈出框扰魂。
  2. :method => :delete屬性帽馋,這為我們的連接上增加了 data-method="delete" 屬性,這樣好爬,ujs 會(huì)把這個(gè)點(diǎn)擊動(dòng)作,會(huì)發(fā)送一個(gè) delete 請(qǐng)求刪除資源,這是符合 REST 要求的烤低。
  3. <%= 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 回傳的資料

未完成

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末尉辑,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子较屿,更是在濱河造成了極大的恐慌隧魄,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,744評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吝镣,死亡現(xiàn)場(chǎng)離奇詭異堤器,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)末贾,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門闸溃,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人拱撵,你說我怎么就攤上這事辉川。” “怎么了拴测?”我有些...
    開封第一講書人閱讀 163,105評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵乓旗,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我集索,道長(zhǎng)屿愚,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,242評(píng)論 1 292
  • 正文 為了忘掉前任务荆,我火速辦了婚禮妆距,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘函匕。我一直安慰自己娱据,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,269評(píng)論 6 389
  • 文/花漫 我一把揭開白布盅惜。 她就那樣靜靜地躺著中剩,像睡著了一般忌穿。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上结啼,一...
    開封第一講書人閱讀 51,215評(píng)論 1 299
  • 那天掠剑,我揣著相機(jī)與錄音,去河邊找鬼郊愧。 笑死澡腾,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的糕珊。 我是一名探鬼主播,決...
    沈念sama閱讀 40,096評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼毅糟,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼红选!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起姆另,我...
    開封第一講書人閱讀 38,939評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤喇肋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后迹辐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蝶防,經(jīng)...
    沈念sama閱讀 45,354評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,573評(píng)論 2 333
  • 正文 我和宋清朗相戀三年明吩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了间学。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,745評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡印荔,死狀恐怖低葫,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情仍律,我是刑警寧澤嘿悬,帶...
    沈念sama閱讀 35,448評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站水泉,受9級(jí)特大地震影響善涨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜草则,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,048評(píng)論 3 327
  • 文/蒙蒙 一钢拧、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧畔师,春花似錦娶靡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽塔鳍。三九已至,卻和暖如春呻此,著一層夾襖步出監(jiān)牢的瞬間轮纫,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工焚鲜, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留掌唾,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,776評(píng)論 2 369
  • 正文 我出身青樓忿磅,卻偏偏與公主長(zhǎng)得像糯彬,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子葱她,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,652評(píng)論 2 354

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