簡體   English   中英

使用ajax表單提交更新頁面元素而無需刷新

[英]update page elements without refresh using ajax form submit

我在同一頁面上有一個帶有嵌套屬性的表單和一個HTML列表元素。 我正在使用AJAX請求處理表單提交。 在提交時,我想保留在同一頁面上並更新列表以顯示剛提交的項目,而無需刷新頁面。

下面的代碼顯示了提交處理程序的javascript。 我希望能夠僅使用jquery將表單數據附加到列表中,但運氣不佳。 我已經嘗試過使用Rails不引人注意的javascript,但在這種情況下也無法使它正常工作。

任何幫助將不勝感激。

$('#new_box').submit(function(event){
    event.preventDefault();

    var cube = newCube($("#box_name").val(), 25, 25, 25);
    addCube(cube);

    var data = {};
    data["box"] = {};
    data["box"]["x"] = cube.position.x;
    data["box"]["y"] = cube.position.y;
    data["box"]["z"] = cube.position.z;

    var formData = $(this).serialize() + '&' + $.param(data);

    var locker_id = $('#my-canvas').data('locker').id;

    $.ajax({
      url: '/lockers/' + locker_id + '/boxes',
      method: 'post',
      dataType: 'json',
      data: formData,
      error: function(){
        alert("Could not add box!");
      },
      success: function(data){
        $('.box-list').append(formData);
      }
    });

  });

列表部分如下:

<ul class="list-group box-list">
    <li class="list-group-item box" id="<%= dom_id(box) %>" data-box="<%= box.to_json %>">
      <%= link_to box.name, "javascript:void(0)" %>
      <span class="badge"><%= box.items.count %></span>
      <ul class="list-group box-items">
        <% box.items.each do |item| %>
        <li class="list-group-item"><%= item.name %></li>
        <% end %>
      </ul>
    </li> 
</ul>
$('.box-list').append($(data).children());

我最終將ajax響應呈現為html部分,然后將該部分附加到ajax請求的成功塊中。

控制器:

respond_to do |format|
      if @box.save
        @item = Item.new
        format.html { render partial: 'boxes/box_list', locals: { box: @box } }
      end
    end

javascript:

$.ajax({
      url: '/lockers/' + locker_id + '/boxes.html',
      method: 'post',
      data: formData,
      error: function(){
        alert("Could not add box!");
      },
      success: function(response){
        $('.box-list').append(response);
        $('input[type=text]').val('');
      }
    });

暫無
暫無

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

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