如何在symfony2中通过ajax提交数据后清除表单字段?

时间:2013-08-21 08:56:59

标签: ajax symfony

my new.html.twig代码如下。如何在表单提交后清除表单字段?

{% extends '::base.html.twig' %}

{% block body -%}
<h1>Proposals creation</h1>

<form action="{{ path('proposals_create') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}
    <p>
        <button type="submit">Create</button>
    </p>
</form>

    <ul class="record_actions">
<li>
    <a href="{{ path('proposals') }}">
        Back to the list
    </a>
</li>
</ul>
<div id="result"></div>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('js/jquery-1.10.2.js') }}" type="text/javascript"></script>
<script type="text/javascript">
 $().ready(function() {
     $("form").submit(function(e) {
         e.preventDefault();
         var $url = $(this).attr('action');
         var $data = $(this).serialize();
         $.ajax({
            type: "POST",
            url: $url,
            data: $data
         }).done(function( result ) {
            if(result.success) {
                $('#result').html('<span>Monetary expense correctly saved!<br/> The data are:<br/>id: '+ result.id +'<br/>descrition: '+ result.description +'<br/>proposalname: '+ result.proposalname +'<br/>status: '+ result.status +'</span>');
            }
         });
     });
 });

 </script>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

使用HTMLFormElement.reset()将所有<form>字段恢复为默认值。

 $("form").submit(function(e) {
     e.preventDefault();
     var $url = $(this).attr('action');
     var $data = $(this).serialize();
     $.ajax({
        type: "POST",
        url: $url,
        data: $data
     }).done(function( result ) {
        if(result.success) {
            $('#result').html('<span> ... </span>');
        }
     });
     this.reset(); // formElement.reset()
 });
  

reset()将表单重置为其初始状态。此方法与单击表单的重置按钮的方法相同。如果表单控件(例如重置按钮)的名称或id为reset,则会掩盖表单的重置方法。