Posting comment with ajax and jquery

2019-08-03 08:25发布

问题:

I want to display the posted comment once the user comments. Just to add it under all of them as facebook does.

I have this:

 // Interceptamos el evento submit
    $('#CommentAddForm').submit(function() {
        alert("entro");
        alert($(this).attr('action'));

        // Enviamos el formulario usando AJAX
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            // Mostramos un mensaje con la respuesta de PHP
            success: function(data) {
                $('#result').html(//????????????);
            }
        });        
        return false;
    }); 

But i don't know very well how it works and i dont know what should i write in the line $('#result').html(//????????????);

The variable URL contains the route which inserts the comment in the DB. And it works well. Any idea? Thanks.

By the way, i have been reading this answer: Ajax/jQuery Comment System But i still don't get it.

回答1:

ok ı finished it and its work fine. when you submit, its appending your comment to commentbox as facebook does.

change your code like this:

var comment=$('.comment').val(); // your comment text box
$.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            // Mostramos un mensaje con la respuesta de PHP
            success: function(data) {

            $('.commentbox').append("</br>"+comment); // list of comments. its inserting your last comment at the end of line.

           }
        });