红宝石POS系统。AJAX 添加项执行两次

ruby POS system. AJAX Adding an item executes twice

提问人:Mike Barrett 提问时间:8/28/2023 最后编辑:DavidMike Barrett 更新时间:9/5/2023 访问量:35

问:

我对 Web 开发还是个新手,刚刚开始将 POS 系统作为一个有趣的小项目进行工作。 我在我的项目页面上非常努力,我基本上需要在一个页面上完成所有 crud,我尝试使用 AJAX 来完成此操作,到目前为止,我有一个您单击的按钮,它显示了具有添加新项目的表单的模式,它可以工作,但似乎执行了两次, 所以我得到了两个相同的项目,但当我手动刷新页面时,它只显示额外的一个。 我所看到的一切都指向了我的 javascript 是如何加载的,但任何帮助都值得赞赏。

这是我的javascript:

document.addEventListener('turbolinks:load', () => {
  // Function to open the "New Item" modal
  newItemButton.addEventListener('click', () => {
    newItemModal.style.display = 'block';
  });

  // Function to open the "Edit Item" modal
  editItemButtons.forEach(button => {
    button.addEventListener('click', () => {
      const itemId = button.dataset.id;
      const formData = new FormData(editItemForm);

      // Use AJAX to fetch item details and populate the form
      fetch(`/items/${itemId}/update_item`, {
          method: 'PATCH', // Use PATCH method for updates
          headers: {
            'X-CSRF-Token': csrfToken,
            'Accept': 'application/json'
          },
          body: formData
        })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(item => {
          const form = editItemModal.querySelector('form');
          form.action = `/items/${itemId}`;
          form.querySelector('[name="item[name]"]').value = item.name;
          form.querySelector('[name="item[cost_price]"]').value = item.cost_price;
          form.querySelector('[name="item[sale_price]"]').value = item.sale_price;
          form.querySelector('[name="item[category]"]').value = item.category;
          editItemModal.style.display = 'block';
        });
    });
  });

  // Function to close the modals when clicking outside of them
  window.addEventListener('click', event => {
    if (event.target === newItemModal || event.target === editItemModal) {
      newItemModal.style.display = 'none';
      editItemModal.style.display = 'none';
    }
  });

  closeButtons.forEach(button => {
    button.addEventListener('click', () => {
      newItemModal.style.display = 'none';
      editItemModal.style.display = 'none';
    });
  });

  newItemForm.addEventListener('submit', event => {
    event.preventDefault();

    const formData = new FormData(newItemForm);
    fetch('/items', {
        method: 'POST',
        headers: {
          'X-CSRF-Token': '<%= form_authenticity_token %>',
          'Accept': 'application/json'
        },
        body: formData
      })
      .then(response => response.json())
      .then(item => {
        // Append the new item to the list without reloading the page
        console.log("adding new item")
        const newRow = itemList.insertRow();
        newRow.innerHTML = `
          <td>${item.name}</td>
          <td>${item.price}</td>
          <td>${item.category}</td>
          <td>
            <button class="edit-item-button" data-id="${item.id}">Edit</button>
            <button class="delete-item-button" data-id="${item.id}">Delete</button>
          </td>
        `;

        // Reset the form and close the modal
        newItemModal.style.display = 'none';
      })
      .catch(error => console.error('Error:', error));
  });
});
class ItemsController < ApplicationController
  def index
    @items = current_user.items # Fetch items for the current user
  end

  def create
    puts 'Create Item action called'
    @item = current_user.items.new(item_params)
    respond_to do |format|
      if @item.save
        puts 'item saved'
        format.html { redirect_to items_path, notice: 'Item was successfully created.' }
        format.json { render json: @item, status: :created }
      else
        puts @item.errors.full_messages
        format.html { render :new }
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def item_params
    params.require(:item).permit(:name, :cost_price, :sale_price, :category)
  end
end
Ruby-on-Rails AJAX 形成 复制的 TurboLink

评论

0赞 David 8/31/2023
您可以验证它运行初始化脚本的次数(例如调试器,将日志添加到事件侦听器)。但是,建议避免添加其他事件侦听器以支持事件委派。github.com/turbolinks/......turbolinks:load

答: 暂无答案