[Rails] AJAX 小技巧
[TOC]
使用 AJAX 注意事項
- 如果是透過 props 把資料代到 Vue 裡面使用,那麼最好在送「建立」或「儲存」的時,可以重新轉譯整個 partial view,避免卡一些髒髒的內容。
- 如果「建立」或「儲存」是透過 AJAX 的方式送出表單,最好鎖上
data-disable="true"
或data-disable_with = "儲存中"
避免表單重複送出。
方法一:在 Rails 本身中使用 AJAX(回傳的是 js 檔)
**優點:**這麼做的好處在於,不用自己透過 AJAX 的方式把資料透過 JSON 送出去,而是可以直接用 Rails 在 <form>
中慣例的 name
。透過 js.erb
來執行送出後的結果。適合用在表單送出後不用使用回傳的資料重新轉譯太多複雜的頁面時。
在 Rails 中使用 AJAX 時,需要在原本的 form 表單中加上 remote: true
。
❗用
remote-true
的話,不能使用querySelector('from').submit()
,要使用Rails.fire(<formElement>, 'submit')
。
在 form 當中加上 remote: true
:
<!-- app/views/subdomains/_form.html.erb -->
<%= form_for :subdomain, remote: true, html: { novalidate: true, id: 'needs-validation' } do |f| %>
<% end %>
如果是使用在 link_to 一樣是使用 remote: true
:
<%= link_to 'foobar', url_path, method: :post, remote: true %>