如何从 Jquery Ajax 获得回复

How to get response from Jquery Ajax

我想从 ajax 请求中获取响应结果,当我单击一个值为 "Accept" 的按钮发送服务器时。 谢谢你的帮助。

我收到错误 419 POST http://localhost:8000/posts/list_post_ajax 419(未知状态)

<table class="table table-bordered">
    <thead class="thead-inverse">
        <tr>
            <th>Post ID</th>
            <th>User ID</th>
            <th>Name User</th>
            <th>Title</th>
            <th>Content</th>
            <th>Datetime</th>
            <th>Status</th>
            <th>Accept</th>
        </tr>
        </thead>
        <tbody>
            @foreach ($posts as $row)
            <tr id="{{ $row->post_id }}"> 
                <td>{{$row->post_id}}</td>
                <td>{{$row->user_id}}</td>
                <th>{{$row->users->name}}</th>
                <td>{{$row->post_title}}</td>
                <td>{{$row->post_content}}</td>
                <td>{{$row->post_datetime}}</td>
                <td>{{$row->post_status}}</td>
            <td>
                <button class="btn btn-success accept-btn" data-postID="{{$row->post_id}}">Accept</button>
            </td>
            </tr>
            @endforeach
        </tbody>
</table>

<script>
    $(document).ready(function () {        
        $('.accept-btn').click(function(){
            var postId = $(this).attr('data-postID');
            console.log(postId)

            $.ajax({
                type: "POST",
                url: "{{route('posts.list_post_ajax')}}",      
                data: { postId: postId },
                dataType: 'JSON',
                success :function(response) {
                    alert("thank u");
                },
            });

        })
    });
</script>

-- 路线:

Route::post('/list_post_ajax','PostController@list_post_ajax')->name('posts.list_post_ajax');
public function list_post_ajax()
    {
       return response()->json('success');
    }

同时发送令牌 数据:{postId:postId,_token:'{{ csrf_token() }}' }

您需要在 post 请求中发送 CSRF 令牌。所以像这样设置 ajax 拳头:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

并立即发送请求

    $.ajax({
        type: "POST",
        url: "{{route('posts.list_post_ajax')}}",      
        data: { postId: postId },
        dataType: 'JSON',
        success :function(response) {
            alert("thank u");
        },
    });

在您的 <head>

中设置元标记
<meta name="csrf-token" content="{{ csrf_token() }}">

你不见了csrf-token

您可以在这里阅读:https://laravel.com/docs/5.8/csrf

长话短说:您有 3 种方法可以解决此问题:

1.全局修复:

将此添加到您的 ajax 设置中(因此它会在您项目的每个页面上执行):

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

并将其添加到您的主布局中:

<meta name="csrf-token" content="{{ csrf_token() }}" />

从现在开始,您将根据每个请求做好准备..

2。仅针对当前端点修复它:

_token 添加到您请求的负载中:

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
}

3。或者从阻止它的中间件中排除你的路由(它可能是 VerifyCSRF):

protected $except = [
        'route/*',
    ];