如何在ajax请求之后在视图中显示更新而不重新加载页面

时间:2016-07-16 21:19:15

标签: jquery ajax symfony

在视图中,我有一个包含数据库数据的表。当我点击编辑时,会出现一个包含编辑表单的模态。当我进行更改并单击保存按钮时,更新将保存在数据库中,并且一切正常。 现在,我想知道如何在视图中显示更新,而不刷新页面。

{% for entity in entities %}
<td>{{ entity.id }}</td>
//....
<td> 
  <a href data-toggle="modal" data-target="#myModal-{{ entity.id }}"
       class="btn btn-mint btn-xs btn-icon btn-circle icon-lg fa fa-pencil">
     </a>
</td>

{% endfor %}

ajax请求

$(document).on('click', ".btn-edit-ajax", function (e) {
    e.preventDefault();
    var $form = $(this).closest('form');
    var action = $form.attr('action');
    var data = $form.serialize();
    var $btn = $('.btn-edit-ajax');

    $btn.prop("disabled", true);

    $.ajax({
        type: 'post',
        dataType: 'json',
        data: data,
        url: action,
        success: function (data) {
            if (data.result == 0) {
                $('.div-errors').replaceWith($(data["view"]));
                $btn.prop("disabled", false);
            }
            else {
                $("#myModal").modal('hide');
                $btn.prop("disabled", false);
            }
        },
        error: function (XHR, status, error) {
            $btn.prop("disabled", false);
            hideLoading();
            console.log(XHR);
            console.log(status);
            console.log(error);
            alert(error);
        }
    });
});

动作

if ($form->isValid()) {
   $em = $this->getDoctrine()->getManager();
   $em->persist($entity);
   $em->flush();

   $response = new JsonResponse();
   return $response;

}

2 个答案:

答案 0 :(得分:0)

{{1}}

答案 1 :(得分:0)

  1. 为每行创建ID

    import java.util.ArrayList;
    
    class Machine{
        public String toString(){
            return "I am a machine";
        }
    }
    
    class MyMachine extends Machine{
        public String toString(){
            return "This is a super Machine";
        }
    }
    
    
    class MyClass<T> {
        public static <T> void showString(T abc){
            System.out.println(abc);
        }
    }
    
    public class myfun {
        public static void main(String[] args) {
            ArrayList<Class> hahalist = new ArrayList<>();
    
            hahalist.add(MyClass.class);
            hahalist.add(Machine.class);
            hahalist.add(MyClass.class);
    
            // Machine abc = new Machine();
            // I can't do this
            // abc = hahalist.get(1);
    
            // I can't do this either
            // hahalist.get(1) abc = new hahalist.get(1)()
        }
    }
    
  2. 从服务器返回更新实体的ID和值,并在这样的ajax中更改成功函数

    <td id='row{{entity.id}}'>{{ entity.id }}</td>
    //....
    <td>