# [Rails4][view]ajax應用實例
###### tags: `Rails4`,`view`
## ajax應用實例1
>重點:在js內用ajax時,若controller有以下語法:
```ruby
respond_to do |format|
format.html
format.js
end
```
>則會回傳"js檔案".注意,是js檔案.
>回傳的js檔案的位置配合controller跟function名稱.
>
>ex:
>app/controllers/admin/ttt_controller.rb的index function,
>相對應的js檔案會位於app/views/admin/ttt/index.js.erb
index.js.erb
```ruby
<% js = escape_javascript(
render(
:partial => "path/to/some/partials",
:locals => { posts: @posts }
)
) %>
$("#content").html("<%= js %>");
```
index.html.erb
```htmlmixed=
<div id="content">
</div>
...
<script>
</script>
{
$.ajax({
url: "/admin/works",
data: {
//此處可傳值進去controller
ttt:{
var1: "this is var1",
var2: "this is var2",
//...
}
},
type: 'GET',
dataType: 'script'
})
}
```
ttt_controller
```ruby
...
def index
@posts = Post.where(var1: ttt_params[:var1])
respond_to do |format|
format.html
format.js
end
end
private
def ttt_params
params.require("ttt").permit(:var1, :var2, :var3)
end
```
---
## 使用link_to 和remote: true屬性及時更新html
https://guides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers
---
## 使用escape_javascript語法去render partial檔案
參考資料:
https://coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easy
## 引用jQuery
```htmlmixed!
<!DOCTYPE html>
<html>
<head>
<title>Ttt</title>
<!--加上 jQuery CDN-->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
```
## routes
```ruby
...
get '/ttt/' => 'ttt#index'
..
```
## controller
```terminal
$rails g controller ttt
```
controllers/ttt_controller.rb
```ruby
class TttController < ApplicationController
def index
end
end
```
## view(重點)
views/ttt/index.html.erb
```ruby!
ttt index
<div id="content">original content</div>
<button id="btn1">btn partial1</button>
<button id="btn2">btn partial2</button>
<script>
$("#btn1").on("click",function(){
$("#content").html("<%= escape_javascript(render partial: 'layouts/partial1' ) %>");
})
$("#btn2").on("click",function(){
$("#content").html("<%= escape_javascript(render partial: 'layouts/partial2' ) %>");
})
</script>
```
## partials
views/layouts/partial1.html.erb
```ruby
this is partial1
<script>
console.log('this is partial1');
</script>
```
views/layouts/partial2.html.erb
```ruby
this is partial2
<script>
console.log('this is partial2');
</script>
```