簡體   English   中英

如何在Rails中實現Ajax?

[英]How to implement Ajax in Rails?

網頁外觀

所以我有一個待辦事項清單,其中包含待辦事項。 對於每個未完成的任務(項目),它旁邊都有一個按鈕,稱為“將項目標記為已完成”。 (請參見button_to方法)每當我單擊該按鈕時,它都應該進入該項目並將其標記為完成。 但是,我正在努力在該項目中實施AJAX,我需要幫助。 我是Rails和Ajax的新手,所以我不知道我在做什么... update.js.erb的警報消息是測試它是否到達那里。

我是否應該創建一個名為_todoitems.html.erb_todolists.html.erb的部分文件? 我還缺少什么,還需要做什么?

這是到目前為止我所做的相關文件...

routes.rb

    todolist_todoitems GET    /todolists/:todolist_id/todoitems(.:format)          todoitems#index
                       POST   /todolists/:todolist_id/todoitems(.:format)          todoitems#create
 new_todolist_todoitem GET    /todolists/:todolist_id/todoitems/new(.:format)      todoitems#new
edit_todolist_todoitem GET    /todolists/:todolist_id/todoitems/:id/edit(.:format) todoitems#edit
     todolist_todoitem GET    /todolists/:todolist_id/todoitems/:id(.:format)      todoitems#show
                       PATCH  /todolists/:todolist_id/todoitems/:id(.:format)      todoitems#update
                       PUT    /todolists/:todolist_id/todoitems/:id(.:format)      todoitems#update
                       DELETE /todolists/:todolist_id/todoitems/:id(.:format)      todoitems#destroy
             todolists GET    /todolists(.:format)                                 todolists#index
                       POST   /todolists(.:format)                                 todolists#create
          new_todolist GET    /todolists/new(.:format)                             todolists#new
         edit_todolist GET    /todolists/:id/edit(.:format)                        todolists#edit
              todolist GET    /todolists/:id(.:format)                             todolists#show
                       PATCH  /todolists/:id(.:format)                             todolists#update
                       PUT    /todolists/:id(.:format)                             todolists#update
                       DELETE /todolists/:id(.:format)                             todolists#destroy
                  root GET    /                                                    todolists#index

todolists / _form.html.erb

<%= form_for(@todolist, remote: true) do |f| %>

todolists_controller.rb

  # PATCH/PUT /todolists/1
  # PATCH/PUT /todolists/1.json
  def update
    respond_to do |format|
      if @todolist.update(todolist_params)
        format.html { redirect_to @todolist, notice: 'Todolist was successfully updated.' }
        format.json { render :show, status: :ok, location: @todolist }
        format.js
      else
        format.html { render :edit }
        format.json { render json: @todolist.errors, status: :unprocessable_entity }
      end
    end
  end

 private
    # Use callbacks to share common setup or constraints between actions.
    def set_todolist
      @todolist = current_user.todolists.find(params[:id])
    end

todolists / show.html.erb

<!-- paginate_items is basically the current user's items -->
<% @paginate_items.each do |item| %>
<div class="list">

  <% if item.due_date > Date.today %>
    <% if item.done? %>
      <a class="complete">
        <%= item.due_date %>
      </a>
      <a class="linkResults">
        <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %><br/> <br/>
      </a>
    <% else %>
      <form class="oneLine">
        <a class="notDue">
          <%= item.due_date %>
        </a>
        <a class="linkResults">
          <%= link_to "#{item.task_title}", [@todolist, item], style: "font-weight: bold;" %>
          <%= button_to "Mark Item as Done", edit_todolist_todoitem_path(@todolist, item), remote: true, id: "done_item_true" %><br/> <br/>
        </a>
      </form>
    <% end %>

todolists / update.js.erb

alert("TEST TEST TEST");

在routes.rb中為ajax請求添加定制路由。 如果您有項目資源,請執行以下操作:

resources :items do 
  collection do
    post 'check_it_off'
  end
end

在項目控制器中添加一個推論控制器操作,並在調用該操作時更新狀態:

def check_it_off
  item_id = params[:item_id]
  item = Item.find(item_id)

  # whatever you are updating, just an example
  item.status = done
  item.save
  render json: {data: "Success"}
end

附加事件以將項目標記為關閉,然后調用ajax請求:

 $(document).on('click', '.some-class', function(e){
   e.preventDefault();

   var itemId = $('#item_id')

   $.ajax({
     type: 'POST',
     url: '/items/check_it_off'
     data: itemId

   }).done(function(response){
      console.log(response)
   })
 })

在您看來,通過說出類似以下內容的方式,為每個項目指定一個與其實際ID相關的ID:id =“ <%= item.id%>”

那應該做。 這基本上是完整的ajax發布請求。

添加一些JavaScript以處理表單上的響應,並更新成功回調上的dom。

$(function(){
  $("#form_id").on("ajax:success", function(e, data, status, xhr) {
    // update the dom here, e.g.
   $("#stuff").append('<img src="check.png"/>');
   }
  ).on("ajax:error", function(e, xhr, status, error) {
    console.log(e, xhr, status, error);
   }
  )
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM