2017-08-07 50 views
0

AJAX通用戶ID和角色我有這樣一個頁面:Laravel和選擇

@extends('admin.master') @section('title', 'Users') 
@section('content') 
<meta name="csrf-token" content="{{ csrf_token() }}"> 
<div class="table-responsive"> 
<table class="table table-striped table-hover"> 
    <thead> 
     <tr> 
      <th>ID</th> 
      <th>Name</th> 
      <th>Email</th> 
      <th>Role</th> 
      <th>Created At</th> 
      <th>Updated At</th> 
      <th>Roles</th> 
      <th>Buttons</th> 
     </tr> 
    </thead> 
    <tbody> 
     @foreach ($users as $user) 
      <tr> 
       <td>{{$user->id}}</td> 
       <td>{{$user->name}}</td> 
       <td>{{$user->email}}</td> 
       <td>{{$user->role}}</td> 
       <td>{{$user->created_at}}</td> 
       <td>{{$user->updated_at}}</td> 
       <td> 
       <input type="hidden" name="id" id="id" value="{{$user->id}}"> 
       <select class="required form-control form-field" name="type" onchange="role(this.value);" id="type"> 
        <option selected disabled>Choose role...</option> 
        @foreach ($roles as $role) 
         <option value={{ $role->id}}>{{ $role->name }}</option> 
        @endforeach 
        </select> 
       </td> 
       <td> 
       <i class="fa fa-pencil-square-o pull-left" style="color: yellow;" aria-hidden="true" data-toggle="modal" data-target="#updateUser"></i> 
       <form method="POST" action={{ url('profile/delete/' . $user->id) }}> 
       {{ method_field('PATCH') }} 
       {{ csrf_field() }} 
       <button type="submit" class="delete" style="border:none;"><i class="fa fa-trash-o pull-right" style="color:red;" aria-hidden="true"></i></button> 
       </form> 
       </td> 
      </tr> 
     @endforeach 
    </tbody> 
</table> 
    <div class="fa add-button"><i class="fa fa-plus fa-2x" style="color: white;" aria-hidden="true" data-toggle="modal" data-target="#createUser"></i></div> 
</div> 
@include('admin.partials.user.updateUser') 
@include('admin.partials.user.createUser') 
@endsection 


function role(role_value) { 
$.ajax({ 
     url: '/test2/' + role_value, 
     method: 'POST', 
     dataType: 'json', 
     success: function(data) { 
      console.log(data); 
     }, 
     error: function(data) { 
      console.log("wrong"); 
     }, 
     headers: { 
     'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') 
     } 
    }); 
} 

對於我有一個數據,並使用下拉菜單可用角色一行中的每個用戶。在我從下拉列表中選擇一個角色後,我想調用一個函數,該函數是ajax請求,它將傳遞選中的role_id,但是我也想通過user_id與我選擇的特定下拉列表相同的行中。我怎樣才能做到這一點?

回答

3

傳遞用戶ID在你的函數類似這樣的

onchange="role(this.value,'{{$user->id}}');" 

然後在你的JS

function role(role_value,user_id) { 
    //Use the user_id and pass it to your ajax 
    console.log(user_id); 
    $.ajax({ 
    ...... 
    }); 
} 
+0

這絕對是很好,謝謝! –

+0

堅持,實際上它說'角色'是不確定的,當我trigget onchange事件 –

+0

你的代碼有問題。檢查錯誤的行。我們剛剛添加了一個新參數。我們沒有刪除任何東西。 –

3

下面應該爲你做的工作:

onchange="role('{{$user->id}}',this.value)"