【问题标题】:ID received from post - send via ajax从帖子收到的 ID - 通过 ajax 发送
【发布时间】:2018-09-30 14:09:36
【问题描述】:

我想从 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%'
});

【问题讨论】:

  • 您只需将$post-&gt;id 发送到服务器,对吧?
  • 是的,没错

标签: ajax laravel jquery-waypoints getvalue


【解决方案1】:

从焦点路径点获取 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
}

【讨论】:

  • 我必须直接从帖子中加载帖子 ID,因为我通过 foreach 将多个帖子加载到视图中。
  • 感谢您的帮助,但我收到一条错误消息:Uncaught TypeError: this.getAttribute is not a function
  • 我得到了关注:t {key: "waypoint-0", options: {…}, element: div#post_container_24.row.waypoint, adapter: t, callback: ƒ, …} adapter: t {$element: n.fn.init(1)} axis: "vertical" callback: ƒ () context: e {element: Window, Adapter: ƒ, adapter: t, key: "waypoint-context-0", didScroll: false, …} element: div#post_container_24.row.waypoint enabled: true group: i {name: "default", axis: "vertical", id: "default-vertical", waypoints: Array(15), triggerQueues: {…}} key: "waypoint-0" options: {context: Window, continuous: true, enabled: true, group: "default", ....
【解决方案2】:

您可以像这样添加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%'
});

【讨论】:

  • 感谢您的帮助,但我收到一条错误消息:this.attr is not a function
猜你喜欢
  • 2020-12-20
  • 2011-02-26
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多