簡體   English   中英

AJAX調用jQuery.append()的結果不適用於Laravel 5.4

[英]The result of AJAX call, jQuery .append() doesn't work with Laravel 5.4

我試圖在我的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>

數據很好,但不幸的是只有附加項無法正常工作。

在您的情況下,可能會出現錯誤,但是您尚未檢查:嘗試按以下方式捕獲錯誤:

    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);
     });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM