我有这个公司列表,我想使用一个按钮来激活/停用它们,而不是刷新页面,所以当我按下“激活/停用”按钮时,公司的状态会改变,按钮也会从激活变为停用,反之亦然。
这是列表视图中的按钮:
<!-- entreprises datatable-->
<div class="panel-body">
<table id="datatable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>RS</th>
<th>Secteur</th>
<th>Telephone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach($resultas as $resultat)
<tr>
<td>{{ $resultat->id}}</td>
<td style="width:100%">{{ $resultat->RS}}</td>
<td>{{ $resultat->secteur}}</td>
<td>{{ $resultat->Tel1}}</td>
<td style=" display:flex">
<div><a href="{{ route('CP_edit',['id'=> $resultat->id]) }}"><button style="background-color:#584F6C" type="button" class="btn btn-secondary btn-sm"> Modifier</button></a></div>
<div>
@if( $resultat->active == 0 )
<a href="{{ route('CP_activate', ['id'=> $resultat->id, 'activation'=> $resultat->active]) }}"><button style="background-color:#3CB371; margin-left:20px;" name="activation" value="{{ $resultat->active }}" type="button" class="btn btn-secondary btn-sm"> Activate</button></a>
@else
<a href="{{ route('CP_activate', ['id'=> $resultat->id, 'activation'=> $resultat->active ]) }}"> <button style="background-color:#B22222; margin-right:20px;" name="activation" value="{{ $resultat->active }}" type="button" class="btn btn-secondary btn-sm"> Deactivate</button></a>
@endif
</div>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
这是更改公司状态的控制器函数:
public function CP_activate(Request $request)
{
$state = $request->activation;
$info = entreprise::find($request->id);
if( $state == 1)
{
$info->active = 0;
$info->save();
}
if( $state == 0)
{
$info->active = 1;
$info->save();
}
}
我正在使用POST方法,我不知道是否应该切换到GET。如果你有任何关于如何让它工作的想法,请。
发布于 2021-03-20 06:19:19
您需要使用Javascript ajax而不是<a>
锚标记
检查
此外,如果您使用vue.js或任何其他前端框架,请检查其实现中的ajax请求
发布于 2021-03-20 06:19:44
因此,最好的方法是使用AJAX请求,而不是普通的表单。
因此,基于您的Blade模板,您已经有了一个JS函数,它监听按钮/链接的单击以切换它。
假设你的函数是重定向/刷新你的页面,你必须这样做:
onclick="activate"
一样,它应该可以工作。< Event
>G29>
function activate(event) {
event.preventDefault(); // <--- this is the magic part that will not go to that URL or refresh the page
/* now you should do an AJAX call to that URL with the data you want,
* so if you want to read the value or anything about that <a> tag, you
* can do event.target and is the same as your previous "this"
*/
}
public function CP_activate(Request $request)
{
$info = entreprise::find($request->id);
$info->active = !$info->active;
$info->save();
}
“缺点”是,如果你打开多个页面(同一页面多次),并点击按钮,它会切换到的活动状态,而不是告诉它有什么状态,但它是少得多的代码,简化,这是超级奇怪的人让同一个页面打开两次或更多……
无论如何,请分享您的activate
JS函数!
https://stackoverflow.com/questions/66715915
复制相似问题