简体   繁体   English

使用ajax表单提交更新页面元素而无需刷新

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

I have a form with nested attributes and an html list element on the same page. 我在同一页面上有一个带有嵌套属性的表单和一个HTML列表元素。 I'm handling the form submission using an AJAX request. 我正在使用AJAX请求处理表单提交。 On submit I want to stay on the same page and update the list to show the item that was just submitted without refreshing the page. 在提交时,我想保留在同一页面上并更新列表以显示刚提交的项目,而无需刷新页面。

The code below shows the javascript for the submit handler. 下面的代码显示了提交处理程序的javascript。 I would like be able to just append the form data to the list using jquery but I'm not having much luck. 我希望能够仅使用jquery将表单数据附加到列表中,但运气不佳。 I have tried using rails unobtrusive javascript but couldn't make that work in this scenario either. 我已经尝试过使用Rails不引人注意的javascript,但在这种情况下也无法使它正常工作。

Any help would be greatly appreciated. 任何帮助将不胜感激。

$('#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);
      }
    });

  });

The list partial is as follows: 列表部分如下:

<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());

I ended up rendering my ajax response as an html partial and then appending that partial in the success block of the ajax request. 我最终将ajax响应呈现为html部分,然后将该部分附加到ajax请求的成功块中。

Controller: 控制器:

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

javascript: 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