从 post 收到的 ID - 通过 ajax 发送

ID received from post - send via ajax

我想从 html 读取 post id 并通过 AJAX 将其发送到控制器。如何获取 post ID ($post->id) 并通过 AJAX 传输?或者有没有更好的方案来保存用户看到的post?

@foreach ($posts as $post)
    <div id="post_container_{{$post->id}}" class="row waypoint">
    </div>
@endforeach

这是我的 AJAX 代码:

$('.waypoint').waypoint(function() {
        $.ajax({
            url: '/posts/view',
            type: "post",
            data:
            success: function(request){
                console.log(request);
            },
            error: function(response){
                console.log(response);
            },
            headers:{
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    }, {
        offset: '100%'
});

从聚焦的航点获取id。

let waypoint_id = this.getAttribute('id'); // something like 'post_container_1'

只获取_

之后的字符串
let post_id = waypoint_id.split("_").pop(); // something like '1'

ajax()函数中

data: {
    post_id: post_id
}

您可以像这样添加 data-id 属性:

@foreach ($posts as $post)
    <div id="post_container_{{$post->id}}" data-id="{{$post->id}}" class="row waypoint">
    </div>
@endforeach

然后使用 attr()

访问它
$('.waypoint').waypoint(function() {
    let post_id = $(this).attr('data-id');   //this specifies the particular post row in focus.
    $.ajax({
        url: '/posts/view',
        type: "post",
        data: {post_id: post_id}
        //and so on. 
    });
}, {
offset: '100%'
});