0

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

@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%'
});
4

2 回答 2

2

从焦点航路点获取 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
}
于 2018-09-30T14:18:10.140 回答
1

你可以像这样添加一个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%'
});
于 2018-09-30T14:58:31.913 回答