我想从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%'
});
答案 0 :(得分: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
}
答案 1 :(得分: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%'
});