简体   繁体   English

如何在Rails中实现Ajax?

[英]How to implement Ajax in Rails?

Webpage Look 网页外观

So I have a Todo List and contains Todo Items. 所以我有一个待办事项清单,其中包含待办事项。 And for each incomplete task(item), there is a button next to it called "Mark Item as Done". 对于每个未完成的任务(项目),它旁边都有一个按钮,称为“将项目标记为已完成”。 (See button_to method) Whenever I click on that button, it should go into that item and mark it as done. (请参见button_to方法)每当我单击该按钮时,它都应该进入该项目并将其标记为完成。 However, I'm struggling to implement AJAX into this project and I need help. 但是,我正在努力在该项目中实施AJAX,我需要帮助。 I'm new to rails and ajax, so I have no clue what I'm doing... The alert message in the update.js.erb is to test if it's reaching there. 我是Rails和Ajax的新手,所以我不知道我在做什么... update.js.erb的警报消息是测试它是否到达那里。

Am I supposed to create a partial file called _todoitems.html.erb or _todolists.html.erb ? 我是否应该创建一个名为_todoitems.html.erb_todolists.html.erb的部分文件? And what else am I missing and what else do I need to do? 我还缺少什么,还需要做什么?

Here are the relevant files of what I've done so far... 这是到目前为止我所做的相关文件...

routes.rb 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 todolists / _form.html.erb

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

todolists_controller.rb 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 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 todolists / update.js.erb

alert("TEST TEST TEST");

Add a custom route for the ajax request in routes.rb. 在routes.rb中为ajax请求添加定制路由。 If you have resources for items make it something like: 如果您有项目资源,请执行以下操作:

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

Add a corollary controller action in your items controller and update the state when that action is called: 在项目控制器中添加一个推论控制器操作,并在调用该操作时更新状态:

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

Attach an event to marking the item off and call your ajax request: 附加事件以将项目标记为关闭,然后调用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)
   })
 })

In your view, give every item an id that relates to their actual id by saying something like: id="<%= item.id %>" 在您看来,通过说出类似以下内容的方式,为每个项目指定一个与其实际ID相关的ID:id =“ <%= item.id%>”

That should do it. 那应该做。 That's basically a full ajax post request. 这基本上是完整的ajax发布请求。

Add some javascript to handle the response on the form and the update the dom on the success callback. 添加一些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