AJAX调用jQuery.append()的结果不适用于Laravel 5.4

时间:2018-10-10 06:41:42

标签: javascript jquery ajax laravel

我正在尝试对Laravel 5.4应用程序中AJAX调用的结果进行.append(),但是附加操作无效,并且控制台中没有错误。

ajax.js:

$( document ).ready(function() {
    $('#storeComment').on('submit', function(e) {
        e.preventDefault();

        // Retrieve form data
        var formData = new FormData();

        var data = $(this).serializeArray();
        $.each(data, function(index, field) {
            formData.set(field.name, field.value);

        });
        axios.post('/comments', formData, { headers: {'Content-Type': 'multipart/form-data' }}
            ).then(function(response) {
            let newComment = "<div class='comment'><p><strong>" + response.data.user.name + "</strong>" 
                + response.data.comment.created_at + "</p><p>" + response.data.comment.comment + "</p><hr></div>";
            console.log(newComment);

            $(".comments").append(newComment);
        });
    });
});

 console.log(newComment); 

结果:

<div class='comment'><p><strong>admin</strong>2018-10-10 06:39:20</p><p>a</p><hr></div>

html:

<div class="comments">
    @forelse ($imageRequest->comments as $comment)
     <div class="comment">
       <p><strong>{{ $comment->user->name }}</strong> {{$comment->created_at}}</p>
       <p>{{ $comment->comment }}</p>
       <hr>
     </div>
    @empty
       <p>@lang('image_request.show.nocomments')</p>
    @endforelse
</div>

数据很好,不幸的是只有附加项无法正常工作。

1 个答案:

答案 0 :(得分:0)

在您的情况下,可能会出现错误,但是您尚未检查:尝试按以下方式捕获错误:

    axios.post('/comments', formData, { headers: {'Content-Type': 'multipart/form-data' }}
        ).then(function(response) {
        let newComment = "<div class='comment'><p><strong>" + response.data.user.name + "</strong>" 
            + response.data.comment.created_at + "</p><p>" + response.data.comment.comment + "</p><hr></div>";
        console.log(newComment);

        $(".comments").append(newComment);
    })
    .catch(function (error) {
       // handle error
        console.log(error);
     });