繁体   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