首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ajax帖子列表仅更新第一个帖子

ajax帖子列表仅更新第一个帖子
EN

Stack Overflow用户
提问于 2021-09-20 10:08:41
回答 2查看 71关注 0票数 0

我有一个用户发送的内容列表,比如tweeting,他们发布一个文本,下面的内容也会显示出来。输入我在Ajax中放了一个ID来更新ID,但是因为帖子在下面,编辑是模态的,所以只有一个表单可以编辑,因为输入的ID是固定的,你能帮助一下吗?

代码语言:javascript
复制
@foreach($consult as $item)
                                <div id="cards" class="card data-id-{{$item->id}}">
                                    <div class="card-header">
                                        <h5 class="card-title">your consult</h5>

                                        <div class="card-tools">
                                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                                <i class="fas fa-minus"></i>
                                            </button>
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-tool " data-toggle="dropdown" aria-expanded="false">
                                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-supported-dps="24x24" fill="currentColor" class="mercado-match" width="24" height="24" focusable="false">
                                                        <path d="M14 12a2 2 0 11-2-2 2 2 0 012 2zM4 10a2 2 0 102 2 2 2 0 00-2-2zm16 0a2 2 0 102 2 2 2 0 00-2-2z"></path>
                                                    </svg>
                                                </button>
                                                <div class="dropdown-menu dropdown-menu-right" role="menu" style="">
                                                    <button data-toggle="modal" data-target="#modal-lg-{{$item->id}}" class="dropdown-item "><i class="fas fa-edit"></i> Edit</button>
                                                    <button  class="dropdown-item deleteskill" data-id="{{$item->id}}" data-token="{{ csrf_token() }}" ><i class="fas fa-trash"></i> Delete</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body" >
                                        <div class="post">
                                            <div class="user-block all-posts-body">
                                                @if(Auth::user()->photo)
                                                    <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/photo/avatar/{{Auth::user()->photo}}">
                                                @else
                                                    <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/img/avatar.png" >
                                                @endif
                                                <span class="username">
                                                      <a href="#">{{Auth::user()->name}}{{Auth::user()->family}}</a>
                                                   </span>
                                                <span class="description">Shared publicly - {{ \Carbon\Carbon::parse($item->created_at)->diffForhumans()}}</span>
                                                <p>
                                                    {{$item->description}}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endforeach

我的模式

代码语言:javascript
复制
    @foreach($consult as $item)
                                <div class="modal fade" id="modal-lg-{{$item->id}}">
                                    <div class="modal-dialog modal-lg">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h4 class="modal-title">update your consult</h4>
                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                    <span aria-hidden="true">&times;</span>
                                                </button>
                                            </div>
                                            <form data-id="{{$item->id}}" method="post" action="{{ route("Consult.update", $item->id) }}" enctype="multipart/form-data">
                                                @csrf
                                                @method('PUT')
                                                <div class="modal-body">
                                                    <textarea   id="description" name="description" class="form-control form-control-sm" type="text" placeholder="What do you want to talk about?" >{{$item->description}}</textarea>
                                                    <div class="alert-message" id="descriptiError"></div>
                                                </div>
                                                <div class="modal-footer justify-content-between">
                                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                                    <button type="button" class="btn btn-primary updateInfo" data-id="{{$item->id}}" data-token="{{ csrf_token() }}">Save changes</button>
                                                </div>
                                            </form>
                                        </div>
                                        <!-- /.modal-content -->
                                    </div>

                                    <!-- /.modal-dialog -->
                                </div>

                            @endforeach

我的ajax代码

代码语言:javascript
复制
 $(".updateInfo").on('click',function(e) {
        e.preventDefault();
        let description = $('#description').val();
        const ConsultId = $(this).attr('data-id');
        var confirmation = confirm("Are you sure you want to update this Consult ?");
        if (confirmation) {
            $.ajax({
                type:"PUT",
                data:{
                    "_token": "{{ csrf_token() }}",
                    description:description,
                },
                url:'/ConsultantsCp/Consult/' + ConsultId,

                success: function(data){
                    swal({title: "Good job", text: "Consult is successfully updated!", type:
                            "success", timer: 1500, buttons: false,}).then(function(){
                            location.reload();
                        }

                    );

                },
                error: function(response) {
                    $('#descriptiError').text(response.responseJSON.errors.description);
                }
            });
        }

    });

enter image description here

enter image description here

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-20 14:54:48

与Rateb的答案相似,但有一点不同

首先,我们必须声明一个javascript函数来初始化我们需要在模式表单中显示的任何内容

其次,我们必须使用必要的内容调用函数。在本例中,当我们单击Edit按钮时,它必须调用js函数

第三个是用来发布数据的逻辑。

请注意,我是如何对description进行编码以保留格式的,并且删除了模式表单中的其他参数,并声明了一个包含item-id的隐藏字段。

代码语言:javascript
复制
@foreach($consult as $item)
    <div id="cards" class="card data-id-{{$item->id}}">
        <div class="card-header">
            <h5 class="card-title">your consult</h5>
            <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                    <i class="fas fa-minus"></i>
                </button>
                <div class="btn-group">
                    <button type="button" class="btn btn-tool " data-toggle="dropdown" aria-expanded="false">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-supported-dps="24x24" fill="currentColor" class="mercado-match" width="24" height="24" focusable="false">
                            <path d="M14 12a2 2 0 11-2-2 2 2 0 012 2zM4 10a2 2 0 102 2 2 2 0 00-2-2zm16 0a2 2 0 102 2 2 2 0 00-2-2z"></path>
                        </svg>
                    </button>
                    <div class="dropdown-menu dropdown-menu-right" role="menu" style="">
                        <button data-toggle="modal" data-target="#edit-modal" onclick="initModal({{$item->id}}, {{json_encode($item->description)}} )"  class="dropdown-item "><i class="fas fa-edit"></i> Edit</button>                       
                        <button  class="dropdown-item deleteskill" data-id="{{$item->id}}" data-token="{{ csrf_token() }}" ><i class="fas fa-trash"></i> Delete</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="card-body" >
            <div class="post">
                <div class="user-block all-posts-body">
                    @if(Auth::user()->photo)
                        <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/photo/avatar/{{Auth::user()->photo}}">
                    @else
                        <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/img/avatar.png" >
                    @endif
                    <span class="username">
                          <a href="#">{{Auth::user()->name}}{{Auth::user()->family}}</a>
                       </span>
                    <span class="description">Shared publicly - {{ \Carbon\Carbon::parse($item->created_at)->diffForhumans()}}</span>
                    <p>
                        {{$item->description}}
                    </p>
                </div>
            </div>
        </div>
    </div>
@endforeach

模式

代码语言:javascript
复制
<div class="modal fade" id="edit-modal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">update your consult</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="edit-modal-form">                   

                    <div class="modal-body">
                        <textarea   id="description" name="description" class="form-control form-control-sm" type="text" placeholder="What do you want to talk about?" ></textarea>
                        <div class="alert-message" id="descriptiError"></div>

                        <input type="hidden" id="item-id-field">
                    </div>
                    <div class="modal-footer justify-content-between">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary updateInfo" >Save changes</button>
                    </div>
                </form>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>

脚本

代码语言:javascript
复制
function initModal(id, description)
{
      // Inialize the modal hidden field with the id value using Jquery
      $("#item-id-field").val(id);
     
       // decode the json and show it in the desciption field in the modal
      var description_decoded = JSON.parse(JSON.stringify(description));
      $("#description").html(description_decoded);
}


$(".updateInfo").on('click',function(e) {
    e.preventDefault();
    let description = $('#description').val();
    const ConsultId = $("#item-id-field").val();
    var confirmation = confirm("Are you sure you want to update this Consult ?");
    if (confirmation) {
        $.ajax({
            type:"PUT",
            data:{
                "_token": "{{ csrf_token() }}",
                description:description,
            },
            url:'/ConsultantsCp/Consult/' + ConsultId,
            success: function(data){
                swal({title: "Good job", text: "Consult is successfully updated!", type:
                        "success", timer: 1500, buttons: false,}).then(function(){
                        location.reload();
                    }
                );
            },
            error: function(response) {
                $('#descriptiError').text(response.responseJSON.errors.description);
            }
        });
    }
});
票数 1
EN

Stack Overflow用户

发布于 2021-09-20 11:16:38

尝试这个例子,它是一个简单的例子,假设你有提供帖子信息的show route和提交编辑的edit route,在这个例子中,我们不提交表单,我们只是用ajax客户端发送一个名为axios的请求,

刀片文件:

代码语言:javascript
复制
 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>

<body>
    @foreach($consult as $item)

    <div id="cards" class="card">
        <div class="card-header">
            <h5 class="card-title">your consult</h5>

            <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                    <i class="fas fa-minus"></i>
                </button>
                <button data-id={{$item['id']}} type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                    edit
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="post">
                <p>
                    {{$item['description']}}
                </p>
            </div>
        </div>
    </div>
    @endforeach

    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Edit post</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <input type="hidden" name="id">
                        <div class="form-group">
                            <label>Description</label>
                            <input name="description" class="form-control">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button name="save-button" type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
    </script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.4/axios.min.js"></script>
</body>

<script>

    const modal = $('#exampleModal')
    const descriptionInput = $('input[name="description"]')
    const idInput = $('input[name="id"]')

    const saveButton = $('button[name="save-button"]')

    modal.on('show.bs.modal', (e) => {

        // getting the id from clicked button
        const postId = e.relatedTarget.getAttribute('data-id')

        // render the required post info 
        axios.get('/posts/' + postId).then(res => {
            descriptionInput.val(res.data.description)
            idInput.val(res.data.id)
        })
    })

    saveButton.on('click', () => {
        // the edit request in your example its /ConsultantsCp/Consult/' + ConsultId
        axios.put('/posts/' + idInput.val(), {
            _token: "{{ csrf_token() }}",
            description: descriptionInput.val(),
        }).then(res => {
            console.log(res)
            modal.modal('toggle')
        })
    })


</script>

</html>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69252631

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档