---
title: PMaster javascript 容易被誤解的j系列
tags: astro, PMaster, javascript
---
最近更新:20200925
# 容易被誤解的j系列~
# js.erb
- [x] 已完成:新增的post可以立即按讚
可以讓js抓到partial檔,用inner html的方式讓原本區塊裡渲染出畫面
```ruby
# posts.js.erb
$('#posts-block').html("<%= j render('items/partials/posts') %>")
```
# Ajax
未來實作:
post計數
實現`不換頁`的效果
Ajax前端送資料的中介,
當function執行時,ajax經過route送到controller,把資料儲存或更新
jQuery
```
function createWorkspace(){
$.ajax({
type: "POST",
url: '/workspaces',
data: {
name: $("#add-workspace-name").val()
},
success: function(result){
if(result.success){
$("#add-workspace-name").val('')
$("#created-workspaces").append(createSidebarRow(result))
alert("新增成功!")
}
else{
alert("新增失敗!")
}
}
});
}
```
workspace controller
```
def create
@workspace = current_user.created_workspaces.new(name: params[:name])
@workspace.save
room_create
render json: {
success: @workspace.save,
id: @workspace.id,
name: @workspace.name
}
end
```
# json
成功的話,把需要的資料打包成json,送到前端做假動作
(讓使用者即時知道已經更新完成)
```
render json: {
success: @workspace.save,
id: @workspace.id,
name: @workspace.name
}
```
# jbuilder
rails做的事情
前後端分離時,拿json
```
json.extract! message, :id, :content, :user_id, :room_id, :created_at, :updated_at
json.url message_url(message, format: :json)
```
eg:
一開始改寫成Vue的時候,
我們有可能會把資料塞在`data-attribute`裡
```
<div id="column" data-list="<%= @columns.to_json(include: :tickets)%>">
</div>
```

這些資料就是從`_conlumn.json.jbuilder`裡拿到的
```
json.extract! column, :id, :name, :kanban_id, :position, :created_at, :updated_at
json.url column_url(column, format: :json)
```
# rails gon gem
從controller送資料去js檔
```
https://github.com/gazay/gon
https://rubygems.org/gems/gon/versions/6.3.2
```
# 參考
[Mei的筆記](https://hackmd.io/lZ4H3LTFQsylBp4-614DAQ)
[龍哥](https://railsbook.tw/chapters/22-api-mode.html)