如何将所选 table 行的 ID 传递到我的 AJAX 函数以获取数据

How can I pass an ID from selected table row to my AJAX function that fetching data

抱歉打扰,我在向我的 AJAX 函数传递 ID 时遇到问题。

我想将所选 table 行的 ID 传递给我的 AJAX 函数,并将其用于我的控制器中的查询

这是我的 table 行的代码

<div class="container">

<h2 style="margin-top: 12px;" class="alert alert-success">Details</h2><br>
    <div class="row">
      <div class="col-12">
      <table class="table table-bordered" id="">
      <thead>
      <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Email</th>
      <td colspan="2">Action</td>
      </tr>
      </thead>
      <tbody id="users-crud">
      @foreach($merchants as $merchant)
      <tr id="user_id_{{ $merchant->id }}">
      <td>{{ $merchant->id}}</td>
      <td>{{ $merchant->first_name }}</td>
      <td>{{ $merchant->email }}</td>
     <td><a id="getData" onClick="getData({{$merchant->id}})" class="btn btn-info">Show</a> 
     </td>
      </tr>
      @endforeach
      </tbody>
      </table>
      {{ $merchants->links() }}
      </div> 
    </div>
  </div>

单击显示 ID 后应将其传递给我的 AJAX 函数, 这是脚本的代码

   <script type=text/javascript>
      $(document).ready(function() {
       });
    
       function getData(id){
      $('#myModal').modal('show');
          $.ajax({  //create an ajax request to display.php
          type: "GET",
       url: "getproducts/",
       // dataType: 'json',
        data: {id: id}, // This will be {id: "1234"}     
        success: function (data) {
       $("#id").html(data.id);
       $("#first_name").text(data.first_name);
       }
       });
    
      };
    
    </script>

ID 将用于我的控制器中的查询,这是我的控制器代码,请注意,我的 where 查询中的数字 1 是硬编码的,我想放置从所选 table

public function getproducts()
{
    $merchants  = DB::table('merchants')
    ->select('merchants.*', 'product.product_name as product_names')
    ->join('product','product.id','=','merchants.id')
    // THE NUMBER 1 IS HARD CODED
    ->where('merchants.id', 1)
    ->paginate(8);
    return response()->json($test, 200);
}

我觉得你的代码没问题。您面临的问题是什么?但是您可以进一步改进代码。

<td><a id="getData" onClick="getData({{$merchant->id}})" class="btn btn-info">Show</a> 

您可以使用全局 class。在 class 中使用相同的 HTML id 也不是好的做法。

<td><a class="merchant_info" data-id="{{$merchant->id}}" class="btn btn-info">Show</a> 

现在需要修改 jQuery 代码

<script type=text/javascript>
  $(document).ready(function() {
    $('.merchant_info').click(function(e){
       e.preventDefault();
       var dataId = $(this).attr("data-id");

       // Now do the Ajax Call etc

    });
  });
</script>

Laravel 控制器中的每个方法都可以将参数“注入”其中,包括 Request $request 变量。在 namespace 声明后将其添加到控制器的顶部:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

然后修改你的方法:

public function getproducts(Request $request) {
   ...
}

然后,从 $request 对象中提取值 1 而不是 hard-coding:

->where('merchants.id', $request->input('id'))

完整的文档可以在这里看到:

https://laravel.com/docs/9.x/requests#accessing-the-request