如何通过<tr>单击按钮通过 ajax 将 a 的单元格值传递给控制器?



我想单独获取每个单元格值。在这里,我包括了我用来获得一个单元格值的jQuery,但它不起作用(我获得了带有.each函数的所有单元格值,但没有单独)。实际上,我想在单击同一行的单元格时将行的所有单元格值传递给控制器。什么是有效的方法?

$(function(){
    $('#product_table').on('click', '#add', function(){
        var p_name = ($(this).closest("tr").find('#p_name').text());
        alert (p_name);
        
       
      /* var token= {{csrf_token()}}
         $.ajax({
            method:"post",
            url:"{{ route('product.edit') }}",
            data: {p_name:p_name, _token:token},
            success:function (response) {
                location.reload();
            }
        });
        $(this).parents("tr").find(".add, .edit").toggle();
        $(".add-new").removeAttr("disabled");
      */
        
    });
});
<table class="table table-bordered table-hover" id="product_table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Details</th>
            <th>Price</th>
            {{--<th>Image(s)</th>--}}
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    @if($products->count()>0)
        @foreach($products as $product)
        <tr>
            <td id="p_name">{{$product->name}}</td>
            <td id="p_details">{{$product->details}}</td>
            <td id="p_price">{{$product->price}}</td>
            <td>
              <a class="add" id="add" data-id="{{$product->id}}" title="Add"></a>
              <a class="edit" title="Edit"></a>
              <a class="delete"  title="Delete" data-id="{{$product->id}}"></a>
            </td>
        </tr>
        @endforeach
    @else
        <tr>
            <td colspan="4" class="text-center bg-danger">No Product Data Found</td>
        </tr>
    @endif
    </tbody>
</table>

您可以在行上循环遍历所有td,并检查是否具有属性ID。然后创建一个数组,然后在以下数组中推动该TD值:

$('#product_table').on('click', '#add', function(){
                dataString = {};
                $(this).closest("tr").find('td').each(function(){
                    let attrId = $(this).attr('id');
                    if (typeof attrId !== typeof undefined && attrId !== false) {
                        dataString[attrId] = $(this).text();
                    }
                });

                 var token = {{csrf_token()}};
                 $.ajax({
                    method:"post",
                    url:"{{ route('product.edit') }}",
                    data: {data:dataString, _token:token},
                    success:function (response) {
                        location.reload();
                    }
                });
                $(this).parents("tr").find(".add, .edit").toggle();
                $(".add-new").removeAttr("disabled");

            });

希望它对您有帮助。

最新更新