weixin_33696106 2016-05-01 21:29 采纳率: 0%
浏览 25

jQuery ajax只工作一次

I'm creatin a quiz bundle and i'm using ajax to load a new question form when submitting one . the problem is that the ajax is working only once when i click next i have a new form but then i keep having the old form .

Any Help ?

this is my view code :

<form method="post" class="ajax"> 
    <div id="form_body">

        {% include 'MoocBundle:Quiz:form.html.twig' with {'form': form} %}
    </div>   

</form>
<script type="text/javascript" src="{{ asset('bundles/mooc/js/jquery-2.1.4.min.js') }}"></script>
<script>
$(document).ready(function(){
        $( ".next" ).on("click", function(e) {

         e.preventDefault();

            $.ajax({
                type: $(this).attr('method'),
                url: "{{ path('quiz_show_next',{'id' : 1}) }}",
                cache: false,

                success: function (data) {
                     $('#form_body').html(data);
                  }
            });
            return false;
        }
        ); 
    });


</script>

my controller action ( i'm creating a new form each time )

public function nextAction(Request $request , $id )
{
        $em = $this->getDoctrine()->getManager();
        $quiz = $em->getRepository('MoocBundle:Quizz')->findOneById($id);
        $this->i++;

        $question = $quiz->getQuestions()->get($this->i);


        $form = $this->createCreateForm($question);
        return $this->render('MoocBundle:Quiz:takeQuiz.html.twig', array('form' => $form->createView()));

}
  • 写回答

2条回答 默认 最新

  • weixin_33736048 2016-05-01 21:45
    关注

    If .next is inside of #form_body then use event delegation. Change:

    $( ".next" ).on("click", function(e) {
    

    To:

    $('#form_body').on('click', '.next', function(e) {
    

    Each time you load ajax content you're replacing .next. Since the .next loaded by ajax was not present at DOM ready, the same code that fired for the original .next would not fire, unless you use event delegation.

    评论

报告相同问题?